python - 熊猫:列中元素的位置条件
问题描述
给定一个数据框,我试图打印出具有特定值的一列中有多少单元格对应于具有其他特定值的另一列的相同索引。在这种情况下,输出应为“2”,因为条件为 df[z]=4 和 df[x]=C,并且只有单元格 10 和 11 符合此要求。我的代码不输出任何结果,而只输出一条警告消息: :5: DeprecationWarning: elementwise comparison failed; 这将在未来引发错误。if (df[df['z']== 4].index.values) == (df[df['x']== 'C'].index.values): :5: DeprecationWarning: elementwise comparison failed ; 这将在未来引发错误。
除了解决这个问题之外,是否还有另一种更“pythonish”的方式来做到这一点而无需 for 循环?
import numpy as np
import pandas as pd
data=[['A', 1,2 ,5, 'blue'],
['A', 1,5,6, 'blue'],
['A', 4,4,7, 'blue']
,['B', 6,5,4,'yellow'],
['B',9,9,3, 'blue'],
['B', 7,9,1,'yellow']
,['B', 2,3,1,'yellow'],
['B', 5,1,2,'yellow'],
['C',2,10,9,'green']
,['C', 8,2,8,'green'],
['C', 5,4,3,'green'],
['C', 8,4 ,3,'green']]
df = pd.DataFrame(data, columns=['x','y','z','xy', 'color'])
k=0
print((df[df['z']==4].index.values))
print(df[df['x']== 'C'].index.values)
for i in (df['z']):
if (df[df['z']== 4].index.values) == (df[df['x']== 'C'].index.values):
k+=1
print(k)
解决方案
尝试:
c=df['z'].eq(4) & df['x'].eq('C')
#your condition
最后:
count=df[c].index.size
#OR
count=len(df[c].index)
输出:
print(count)
>>>2
推荐阅读
- mpi - MPI:每个节点打印日志
- r - ggplot:有没有办法在 y 轴的右侧添加颜色编码的条形注释?
- apache-kafka - KSQLDB - 从 debezium cdc 源连接器获取数据并将 Stream 与表连接
- c# - 在不创建类型的情况下更改 YAML 文档
- r - 如何使用 R 中的 data.table 对多行、多列进行平均?
- android-studio - android studio 和插件升级到 4.2.2 后,classpath 应该使用哪个 Gradle 版本?
- javascript - 使用扩展名或其他方式在无名函数中编辑变量
- python - 如何从 Google 新闻中抓取图片?
- c# - 将 response.content 保存为 PDF (C#)
- python - 在 Pandas 中估算缺失的时间戳索引?