计算多个熊猫列中的出现次数

时间:2018-08-01 11:09:20

标签: python pandas

dg  se
29  10
37  22
3   13
15  7
42  20
31  23
26  17
7   1
36  19
5   7
21  5
37  13
37  6
2   24

在上面的数据框中,我想计算0-30、30-40和> 40之间的每列值中出现的百分比;以及两个列的值都在0-30到30-40之间的出现百分比。我当时在考虑使用熊猫hist函数,但这不能满足我的要求

1 个答案:

答案 0 :(得分:1)

使用cut合并两个列:

bins = [0, 30, 40, np.inf]
labels = ['0-30','30-40','40+']
dg = pd.cut(df['dg'], bins=bins, labels = labels, include_lowest=True)
se = pd.cut(df['se'], bins=bins, labels = labels, include_lowest=True)

然后是value_counts

dg_per = dg.value_counts(normalize=True)
print (dg_per)
0-30     0.571429
30-40    0.357143
40+      0.071429
Name: dg, dtype: float64

se_per = se.value_counts(normalize=True)
print (se_per)
0-30     1.0
40+      0.0
30-40    0.0
Name: se, dtype: float64

对于两列中的相同值,请先过滤:

both = (dg[dg == se])
print (both.value_counts(normalize=True))
0-30     1.0
40+      0.0
30-40    0.0
Name: dg, dtype: float64
相关问题