Home > OS >  How do I search a pandas dataframe to get the row with a cell matching a specified value?
How do I search a pandas dataframe to get the row with a cell matching a specified value?

Time:11-06

I have a dataframe that might look like this:

print(df_selection_names)

                             name
0  fatty red meat, like prime rib
0                         grilled

I have another dataframe, df_everything, with columns called name, suggestion and a lot of other columns. I want to find all the rows in df_everything with a name value matching the name values from df_selection_names so that I can print the values for each name and suggestion pair, e.g., "suggestion1 is suggested for name1", "suggestion2 is suggested for name2", etc.

I've tried several ways to get cell values from a dataframe and searching for values within a row including

# number of items in df_selection_names = df_selection_names.shape[0]
# so, in other words, we are looping through all the items the user selected
for i in range(df_selection_names.shape[0]):
    # get the cell value using at() function
    # in 'name' column and i-1 row
    sel = df_selection_names.at[i, 'name']
    # this line finds the row 'sel' in df_everything
    row = df_everything[df_everything['name'] == sel]

but everything I tried gives me ValueErrors. This post leads me to think I may be way off, but I'm feeling pretty confused about everything at this point!

CodePudding user response:

https://pandas.pydata.org/docs/reference/api/pandas.Series.isin.html?highlight=isin#pandas.Series.isin

df_everything[df_everything['name'].isin(df_selection_names["name"])]
  • Related