【问题标题】:Filtering pandas dataframe using dictionary for column values使用字典过滤熊猫数据框以获取列值
【发布时间】:2019-04-04 18:24:59
【问题描述】:

前提

我需要使用字典作为大型数据帧的过滤器,其中键值对是不同列中的值。 该字典是使用dict(zip(df.id_col, df.rank_col)) 从一个单独的数据帧中获得的,因此如果字典不是最好的方法,则可以更改。

这与这个问题非常相似:Filter a pandas dataframe using values from a dict 但从根本上(我认为)不同,因为我的字典包含列配对值:

示例数据

df_x = pd.DataFrame({'id':[1,1,1,2,2,2,3,3,3], 
'B':[1,1,1,0,1,0,1,0,1], 'Rank':['1','2','3','1', '2','3','1','2','3'],'D':[1,2,3,4,5,6,7,8,9]})
filter_dict = {'1':'1', '2':'3', '3':'2'}

对于这个数据框df_x,我希望能够查看过滤器字典并将其应用于一组列,这里是idRank,因此数据框被缩减为:

实际的源数据帧大约有 1M 行,字典是 >100 个键值对。 感谢您的帮助。

【问题讨论】:

    标签: python pandas dictionary filter


    【解决方案1】:

    您可以通过isin查看

    df_x[df_x[['id','Rank']].astype(str).apply(tuple,1).isin(filter_dict.items())]
    Out[182]: 
       id  B Rank  D
    0   1  1    1  1
    5   2  0    3  6
    7   3  0    2  8
    

    【讨论】:

    • 这不起作用,因为两列都是 int64;不过很容易改成astype(int)!谢谢(再次)W-B!!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-25
    • 2019-05-21
    • 2020-08-08
    • 2021-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多