【问题标题】:How to query pandas dataframe using a specific value? [duplicate]如何使用特定值查询熊猫数据框? [复制]
【发布时间】:2016-03-28 16:23:35
【问题描述】:

我有包含以下内容的熊猫数据框:

    A   B     C  D
0 red, t1, blue, 1
1 red, t1, yellow, 2
2 red, t0, green, 1
3 red, t0, blue, 1
4 red, t0, blue, 2
5 green, t1, yeallow, 1
6 green, t0, red, 1
7 green, t0, yellow, 1
8 blue, t0, yellow, 1
9 blue, t1, red, 1
10 yellow, t1, red, 3

例如,如何提取A 等于'green'B 等于t0 的所有行?

【问题讨论】:

  • df[df.A.str.contains("green") & df.B.str.contains("t0")] 因为您使用了“包含”一词。如果你想要完全匹配,df[(df.A == "green") & (df.B == "t0")]
  • 请将此添加为答案。
  • 我不喜欢问题在您提供的链接中的表述方式。所以,我认为最好有一个单独的问题,有一个例子和一个简短的答案,正如@ayhan 给出的那样
  • 这不会检测C列中的颜色,但您可以调整方法如下。定义set_of_needed_words。写df = df[df.apply(lambda s: s.isin(set_of_desired_words))]

标签: python pandas


【解决方案1】:

正如@ayhan 所回答的,

部分字符串匹配:

df[df.A.str.contains("green") & df.B.str.contains("t0")]

精确字符串匹配:

df[(df.A == "green") & (df.B == "t0")]

【讨论】:

  • 这有效,但显然只适用于列AB。所以像['red', 't1', 'green', 0] 这样的行将被省略。我不清楚这是否符合您的意图。
  • 对不起,在我的问题中,我的意思正是如此(更正了问题)。
猜你喜欢
  • 2020-07-28
  • 2017-05-19
  • 2012-11-05
  • 2018-08-03
  • 2016-12-02
  • 2019-12-29
  • 2020-04-21
  • 2021-09-06
  • 2021-10-25
相关资源
最近更新 更多