Skip to main content
 首页 » 编程设计

python之使用 `Dataframe.value_counts()`时不指定列名如何实现 `Series.value_counts`

2025年05月04日14langtianya

比如我得到的dataframe如下:

    PassengerId   Survived    Pclass     
0   1             0           3  
1   2             1           1  
2   3             1           3  

并且在调用df.value_counts()之后,我可以得到所有列的value_counts(),而无需每次都指定一列,这可能是这样的:

1      1 
2      1 
3      1 
Name: PassengerId, dtype: int64 
 
0      1 
1      2 
Name: Survived, dtype: int64 
 
3      2 
1      1 
Name: Survived, dtype: int64 

我想知道如何实现它。
谁能帮帮我?
提前致谢。

请您参考如下方法:

有 2 个解决方案 DataFrame.apply用于按列应用函数,但索引按其交集对齐,因此添加了 NaN:

df1 = df.apply(pd.value_counts) 
print (df1) 
   PassengerId  Survived  Pclass 
0          NaN       1.0     NaN 
1          1.0       2.0     1.0 
2          1.0       NaN     NaN 
3          1.0       NaN     2.0 
 
df1 = df.apply(pd.Series.value_counts) 
print (df1) 
   PassengerId  Survived  Pclass 
0          NaN       1.0     NaN 
1          1.0       2.0     1.0 
2          1.0       NaN     NaN 
3          1.0       NaN     2.0 

为避免可能使用 SeriesGroupBy.value_counts :

df1 = df.stack().groupby(level=1).value_counts().rename_axis(('a','b')).reset_index(name='c') 
print (df1) 
             a  b  c 
0  PassengerId  1  1 
1  PassengerId  2  1 
2  PassengerId  3  1 
3       Pclass  3  2 
4       Pclass  1  1 
5     Survived  1  2 
6     Survived  0  1 

或原始解决方案 DataFrame.stack :

df1 = (df.apply(pd.Series.value_counts) 
         .stack() 
         .astype(int) 
         .rename_axis(('a','b')) 
         .reset_index(name='c') 
print (df1) 
   a            b  c 
0  0     Survived  1 
1  1  PassengerId  1 
2  1     Survived  2 
3  1       Pclass  1 
4  2  PassengerId  1 
5  3  PassengerId  1 
6  3       Pclass  2