计算DataFrame每列中值出现的次数

时间:2019-03-07 21:30:23

标签: python pandas dataframe

我有以下数据框:

df = pd.DataFrame(np.array([[4, 1], [1,1], [5,1], [1,3], [7,8], [np.NaN,8]]), columns=['a', 'b'])

    a    b
0   4    1
1   1    1
2   5    1
3   1    3
4   7    8
5   Nan  8

现在我想对列中的值1到9进行value_counts(),这应该给我以下内容:

    a    b
1   2    3
2   0    0
3   0    1
4   1    0
5   1    0
6   0    0
7   1    0
8   0    2
9   0    0

这意味着我只计算每列中1到9值的出现次数。如何才能做到这一点?我想获得这种格式,以便以后可以应用df.plot(kind='bar', stacked=True)来获得e堆叠的条形图,其中x轴的离散值从1到9,y轴的a和b的计数。

2 个答案:

答案 0 :(得分:5)

使用pd.value_counts

df.apply(pd.value_counts).reindex(range(10)).fillna(0)

enter image description here

答案 1 :(得分:2)

在每一列上使用np.bincount

df.apply(lambda x: np.bincount(x.dropna(),minlength=10))

   a  b
0  0  0
1  2  3
2  0  0
3  0  1
4  1  0
5  1  0
6  0  0
7  1  0
8  0  2
9  0  0

或者,使用列表推导代替apply

pd.DataFrame([
        np.bincount(df[c].dropna(), minlength=10) for c in df
    ], index=df.columns).T

   a  b
0  0  0
1  2  3
2  0  0
3  0  1
4  1  0
5  1  0
6  0  0
7  1  0
8  0  2
9  0  0
相关问题