How to check if a value is in the list in selection from pandas data frame?

后端 未结 3 829
闹比i
闹比i 2020-11-30 02:36

Looks ugly:

df_cut = df_new[
             (
             (df_new[\'l_ext\']==31) |
             (df_new[\'l_ext\']==22) |
             (df_new[\'l_ext\']==30         


        
相关标签:
3条回答
  • 2020-11-30 02:44

    Overview: How to use group by to get a list then use the list as a subquery using isin? Suppose you create a list using a dataframe group by and you want to see the descriptions that match with the iucr code. Start by creating a groupby list for the top 40 iucr codes then use the isin using the groupby index to access the iucr codes. Apply the resulting true or false list to the dataframe and get an unique list of descriptions.

    plt.figure(figsize=(22,6))
    iucr=df_sas.groupby(['IUCR'])['Arrest'].sum().nlargest(40).sort_values(ascending=False)
    iucr.plot.bar()
    plt.show()
    
    arrest_descriptions=df_sas[df_sas['IUCR'].isin(iucr.index)]['Description'].unique()
    arrest_descriptions=np.sort(arrest_descriptions)
    for item in arrest_descriptions:
        print(item)
    
    0 讨论(0)
  • 2020-11-30 02:49

    Use isin

    df_new[df_new['l_ext'].isin([31, 22, 30, 25, 64])]
    
    0 讨论(0)
  • 2020-11-30 03:01

    You can use pd.DataFrame.query:

    select_values = [31, 22, 30, 25, 64]
    df_cut = df_new.query('l_ext in @select_values')
    

    In the background, this uses the top-level pd.eval function.

    0 讨论(0)
提交回复
热议问题