Pandas计算数据帧内的值

问题描述 投票:0回答:4

我有一个如下所示的数据框:

     A     B     C
1    1     8     3
2    5     4     3
3    5     8     1

我想要计算值,以便使df像这样:

       total
1        2
3        2
4        1
5        2
8        2

大熊猫有可能吗?

pandas dataframe
4个回答
2
投票

随着np.unique -

In [332]: df
Out[332]: 
   A  B  C
1  1  8  3
2  5  4  3
3  5  8  1

In [333]: ids, c = np.unique(df.values.ravel(), return_counts=1)

In [334]: pd.DataFrame({'total':c}, index=ids)
Out[334]: 
   total
1      2
3      2
4      1
5      2
8      2

随着pandas-series -

In [357]: pd.Series(np.ravel(df)).value_counts().sort_index()
Out[357]: 
1    2
3    2
4    1
5    2
8    2
dtype: int64

2
投票

你也可以使用stack()groupby()

df = pd.DataFrame({'A':[1,8,3],'B':[5,4,3],'C':[5,8,1]})
print(df)
    A   B   C
0   1   5   5
1   8   4   8
2   3   3   1

df1 = df.stack().reset_index(1)

df1.groupby(0).count()

    level_1
0   
1   2
3   2
4   1
5   2
8   2

1
投票

其他替代方案可能是使用stack,然后是value_counts,结果更改为框架,最后对索引进行排序:

count_df = df.stack().value_counts().to_frame('total').sort_index()
count_df

结果:

     total
1      2
3      2
4      1
5      2
8      2

0
投票

使用np.unique(, return_counts=True)np.column_stack()

pd.DataFrame(np.column_stack(np.unique(df, return_counts=True)))

收益:

   0  1
0  1  2
1  3  2
2  4  1
3  5  2
4  8  2
© www.soinside.com 2019 - 2024. All rights reserved.