<jupyter_start><jupyter_text>Selecting Rows in a DataFrameselect data by using row numbers and/or column numbers.<jupyter_code>import pandas as pd
# read a csv file
pd.read_csv("data\stock_data_simple.csv")
# read csv and store result in variable
df = pd.read_csv("data\stock_data_simple.csv") 
# print out dataframe 
df
# sort by annual sales and save dataframe in variable
df = df.sort_values("annual_sales", ascending=False)
df<jupyter_output><empty_output><jupyter_text>Selecting Rows (Multiple Ways) a. Select the first 3 rows of a DataFrame<jupyter_code># since rows numbers start at 0 in Pandas, 0 is first row
df.iloc[0:3,:]<jupyter_output><empty_output><jupyter_text>b. Select between row 4 and row 7<jupyter_code># note that to include row 7, need to specify 8 as last row
df.iloc[4:8,:]<jupyter_output><empty_output><jupyter_text>c. Select all rows after a row<jupyter_code># since there are 10 rows in CSV File, we get the last 6
df.iloc[4: ,:]<jupyter_output><empty_output><jupyter_text>d. Select a Specific Row (fyi... there are multiple ways)Say we wanted to select the the row for Microsoft<jupyter_code># we could use the ticker column
df
df['ticker'] == "MSFT"
# if we wrap the statment above inside the original dataframe using square brackets
df[df['ticker'] == "MSFT"]
# or can use isin
df['ticker'].isin(["MSFT"])
# again, wrap in square brackets
df[df['ticker'].isin(["MSFT"])]
# we could store the row in a new variable'
df_msft = df[df['ticker'].isin(["MSFT"])]
# we can also get the row number
df_msft.index[0]
# or we can store the row number one line
row_number = df[df['ticker'] == "MSFT"].index[0]
print(row_number)<jupyter_output>6<jupyter_text>Question: How would you select the companies with annual sales less than MSFT?In other words, how do we select all companies after MSFT? Hint: Check example (c)<jupyter_code>df<jupyter_output><empty_output><jupyter_text>Since we know the row number (which we got in previous example d)<jupyter_code>row_number<jupyter_output><empty_output><jupyter_text>and we know how to get rows after a value (Example C. Select all rows after a row )<jupyter_code>df.iloc[6: ,:]
df.iloc[row_number:,:]<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.10761513907888737, 'fraction_numerical': 0.008663930688554491, 'mean_word_length': 6.240924092409241, 'pattern_counts': {'":': 0, '<': 32, '<?xml version=': 0, '>': 32, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '403936', 'license': 'MIT', 'n_tokens_mistral': 786, 'n_tokens_neox': 755, 'n_words': 256, 'path': '04-pandas-other/pandas-selecting-rows.ipynb', 'repo_name': 'ryansmccoy/20191105-meetup-from-spreadsheets-to-dataframes', 'size': '2193'}