【问题标题】:Python - Filter DataFrame by flexible length dict [duplicate]Python - 通过灵活长度的字典过滤 DataFrame [重复]
【发布时间】:2017-09-10 18:20:49
【问题描述】:

我有一个这样的 DataFrame:

    A  B  C
1   1  3  5
2   1  3  6
3   2  4  7
4   2  4  8

我知道我可以过滤固定列如下:

df[df[A]==1 & df[B]==3]

但是如果我想通过灵活的dict长度过滤DataFrame:

dict = {'A':1, 'B':3, 'C':5]}

dict = {'A':2, 'B':4}

我可以得到:

    A  B  C 
1   1  3  5

    A  B  C
3   2  4  7
4   2  4  8

我该如何解决这个问题?

【问题讨论】:

  • 我觉得你需要this

标签: python pandas dictionary dataframe


【解决方案1】:

如果您的字典在列表中包含其值,那么您可以将其传递给 DataFrame isin 方法。

d = {'A':[1], 'B':[3], 'C':[5]}
df[df.isin(d)[list(d.keys())].all(axis=1)]

   A  B  C
1  1  3  5

如果您的字典中有很多项目,您可以像这样自动将值转换为一个项目列表。

{k:[v] for k,v in d.items()}

【讨论】:

    猜你喜欢
    • 2015-12-22
    • 2016-02-15
    • 2016-03-03
    • 1970-01-01
    • 1970-01-01
    • 2015-02-16
    • 1970-01-01
    • 2017-03-06
    • 1970-01-01
    相关资源
    最近更新 更多