在两列中查找1和0的组合数

2024-04-25 12:19:29 发布

您现在位置:Python中文网/ 问答频道 /正文

输入:

            X   Y
Hyderabad   1   1
Bangalore   0   1
Goa         1   1
Chennai     0   1
Hyderabad   0   1
Goa         0   0
Chennai     0   1
Goa         0   0
Hyderabad   1   0
Chennai     0   1
Chennai     1   1
Goa         0   1
Bangalore   0   0
Bangalore   0   1

预期产量:

        X   
        0   1
Y   0   3   1
    1   7   3

Tags: 产量chennaibangalorehyderabadgoa
2条回答

我的意思是,假设它是熊猫数据帧(称为df

from collections import Counter

counter = Counter()
for row in df.itertuples():
    counter[row.X, row.Y] += 1

输出:

 Counter({(0, 0): 3, (0, 1): 7, (1, 0): 1, (1, 1): 3})

假设您有一个pandas数据帧,一个选项是使用pandas.crosstab返回另一个数据帧:

import pandas as pd

df = pd.read_csv('file.csv')
res = pd.crosstab(df['X'], df['Y'])

print(res)

Y  0  1
X      
0  3  7
1  1  3

如果需要字典结果,也可以使用collections.Counter解决方案:

res = Counter(zip(df['X'].values, df['Y'].values))

相关问题 更多 >