python - 根据不同列上的行组合进行选择 pandas

标签 python pandas

我有以下 pandas 数据框。

ID  col1 col2    value
1    4    New     20
2    4    OLD     30
3    5    OLD     60
4    5    New     50
5    3    New     70

我只想选择具有以下规则的行。 col1 中的值 4 和 3 应位于 New 中,5 应位于 col2 中的 Old 中。以其他方式删除其他行。

ID  col1 col2    value
1    4    New     20
3    5    Old     60
5    3    New     70

任何人都可以在 Python pandas 中帮忙解决这个问题吗?

最佳答案

使用DataFrame.query过滤器由 in 链接,由 & 链接(按位 AND),第二个条件链由 | 链接(按位 OR) :

df1 = df.query("(col1 in [4,3] & col2 == 'New') | (col1 == 5 & col2 == 'OLD')")
print (df1)
   ID  col1 col2  value
0   1     4  New     20
2   3     5  OLD     60
4   5     3  New     70

或者使用boolean indexingSeries.isin :

df1 = df[df['col1'].isin([3,4]) & df['col2'].eq('New') | 
         df['col1'].eq(5) & df['col2'].eq('OLD')]

关于python - 根据不同列上的行组合进行选择 pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70272761/

相关文章:

python - 仅从数据框中选择每个月的最后一周 - Python/Pandas

python - 将数据帧转换为不带括号的记录列表

python - Amazon S3 权限错误 403,简单上传文本文件

Pythonic 相当于 ./foo.py < bar.png

python - Cookie Cumbler 在 Zope 中如何工作?

python - 随机行走 Pandas

python - 当特定数量不在特定列中时如何删除数据框的行?

python - 通过列表理解的频率数据框?

python - 将嵌套在两个字典下的列表转换为 DataFrame

python - .aggregate() 中使用的 Django @property