python - 如何根据柱状组的多(其他列)条件选择数据框行?

标签 python pandas group-by conditional-statements

将以下数据框复制到剪贴板:

  textId   score              textInfo
0  name1     1.0            text_stuff
1  name1     2.0  different_text_stuff
2  name1     2.0            text_stuff
3  name2     1.0  different_text_stuff
4  name2     1.3  different_text_stuff
5  name2     2.0  still_different_text
6  name2     1.0              yoko ono
7  name2     3.0     I lika da Gweneth
8  name3     1.0     Always a tradeoff
9  name3     3.0                What?!

现在使用

import pandas as pd
df=pd.read_clipboard(sep='\s\s+')

将其加载到您的环境中。如何对这个数据框进行切片,使得 所有 特定 textId 的行如果 score 返回那一组textId包括至少一个 score等于 1.0、2.0 和 3.0?在这里,所需操作的结果将排除 textIdname1 自其 score组缺少 3.0 并排除 name3,因为它的 score组缺少 2.0:

  textId   score              textInfo
0  name2     1.0  different_text_stuff
1  name2     1.3  different_text_stuff
2  name2     2.0  still_different_text
3  name2     1.0              yoko ono
4  name2     3.0     I lika da Gweneth

尝试

  1. df[df.textId == "textIdRowName" & df.score == 1.0 & df.score == 2.0 & & df.score == 3.0]是不对的,因为条件没有起作用 在 textId 上组,但只有个别行。如果这可以 重写以匹配 textId组然后它可以被放置 在 for 循环中并提供唯一的 textIdRowName。这样的功能 会收集 textId 的名字在一系列中(比如 textIdThatMatchScore123 ) 然后可以用来切片原始 df 喜欢df[df.textId.isin(textIdThatMatchScore123)] .
  2. 失败于 groupby .

最佳答案

这里有一个解决方案 - groupby textId,然后只保留那些唯一的 score 值是 [1.0, 2.0 的超集 (>=) 的组, 3.0]

In [58]: df.groupby('textId').filter(lambda x: set(x['score']) >= set([1.,2.,3.]))
Out[58]: 
  textId  score              textInfo
3  name2    1.0  different_text_stuff
4  name2    1.3  different_text_stuff
5  name2    2.0  still_different_text
6  name2    1.0              yoko ono
7  name2    3.0     I lika da Gweneth

关于python - 如何根据柱状组的多(其他列)条件选择数据框行?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36605535/

相关文章:

python - 在 Pandas 中保存 csv 时删除索引列

python - 在 python pandas 数据框中分箱(不是手动设置分箱)

python - Pandas - 根据日期将数据框拆分为多个数据框?

Python给定一个N个整数的数组A,以O(n)的时间复杂度返回A中没有出现的最小正整数(大于0)

python - 覆盖抽象基类属性会影响其他子类吗?

python - 来自 Pandas Dataframe 的条形图

pandas - (pandas) 为什么 .bfill().ffill() 对组的作用与 ffill().bfill() 不同?

Python3.3 - 致命的 Python 错误 : Py_Initialize: Unable to get the locale encoding

python - Pandas :将多列绘制为相同的 x 值

scala - GroupBy 多列作为键并对多列求和,如 sql 吗?