输入:
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
答案 0 :(得分:1)
我的意思是,假设它是一个pandas数据帧(称为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})
答案 1 :(得分:1)
假设您有一个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))