【问题标题】:How Filter dataframe with dictionary in pandas?如何在熊猫中使用字典过滤数据框?
【发布时间】:2021-12-25 12:10:40
【问题描述】:

我的示例 DataFrame 是:

file Voucher_stand
90.txt SCA
90.txt SCB
60.txt WFA
60.txt WFO
90.txt SCA
50.txt SCA
80.txt SCA
100.txt SCA

我想定义一个字典,根据它我可以选择一些列,但是每个文件在 Voucher_stand 列中都有自己的代码,如何根据 Voucher_stand 和文件通过字典过滤这个 DataFrame 而不是每次都使用列表?

例如,在字典中定义 Voucher_Stand 和文件,然后根据该字典过滤我的 DataFrame:

code = {'90.txt':['SCA', 'SCB'], '60.txt':['WFA', 'WFO']}

【问题讨论】:

    标签: python pandas dataframe dictionary


    【解决方案1】:

    试试这个:

    pd.DataFrame(df.set_index('file').groupby('file')['Voucher_stand'].apply(list)).T.reset_index(drop=True)
    

    您可以通过调用.to_dict()dict 的形式获取它:

    pd.DataFrame(df.set_index('file').groupby('file')['Voucher_stand'].apply(list)).T.reset_index(drop=True).to_dict()
    

    【讨论】:

      【解决方案2】:

      您可以使用items 遍历字典,并使用相等比较键和isin 来过滤所需的行以用于Voucher_stand 代码列表。然后,将行的索引作为列表获取并将其保存到变量中。使用iloc 仅选择符合条件的行。

      import pandas as pd
      
      df = pd.read_csv('sample.csv', sep='\s+')
      print(df)
      
      CODE = {'90.txt':['SCA', 'SCB'], '60.txt':['WFA', 'WFO']}
      
      filtered_rows = []
      for k,v in CODE.items():
          filtered_rows += df[(df['file'] == k) & df['Voucher_stand'].isin(v)].index.to_list()
      
      result = df.iloc[filtered_rows]
      print(result)
      

      结果的输出

           file Voucher_stand
      0  90.txt           SCA
      1  90.txt           SCB
      4  90.txt           SCA
      2  60.txt           WFA
      3  60.txt           WFO
      

      【讨论】:

      • 在此 DataFrame 的另一个示例中,我使用您的代码,但得到另一个答案:s4.uupload.ir/files/1_3ijq.png
      • @amin-jebeli 我看不出有任何不工作的理由。 groupby 之前的c1 的输出是否符合预期?
      • @n1colas-m c1 在 groupby 之前不能正常工作,它实际上适用于文件 365-240,但对于 240-180 它不会过滤字典中包含的代码
      猜你喜欢
      • 1970-01-01
      • 2019-04-04
      • 2021-12-25
      • 2023-03-14
      • 2015-09-24
      • 2021-04-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多