首页 > 解决方案 > 熊猫:列中元素的位置条件

问题描述

给定一个数据框,我试图打印出具有特定值的一列中有多少单元格对应于具有其他特定值的另一列的相同索引。在这种情况下,输出应为“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)

标签: pythonpandasindexingconditional-statements

解决方案


尝试:

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

推荐阅读