python - 如何在 Pandas 中重新格式化 value_counts() 分析以获取大量列

标签 python pandas dataframe

我的数据集由数百列和数千行组成

In [119]:
df.columns
Out[119]:
Index(['column 1', 'column2',
       ...
       'column 100'],
      dtype='object', name='var_name')

通常我会对每一列执行 value_counts() 来查看分布情况。

In [121]:
a = df['column1'].value_counts()
In [122]:
a
Out[122]:
1     77494
2      5389
0      2016
3       878
Name: column 1, dtype: int64

但是对于这个数据框,如果我对每一列都这样做,这将使我的笔记本非常困惑,如何自动化?有什么功能可以帮忙吗?

如果您有其他信息,我的所有数据都是int64,但我希望最佳答案能够提供适用于每种情况的解决方案。我想在 pandas dataframe 中做出解决方案答案。

根据@MaxU的建议,这是我的简化数据框版本

df

id  column1  column2 column3
1         3        1       7
2         3        2       8
3         2        3       7
4         2        1       8
5         1        2       7

我的预期输出是:

column 1   count
1          1
2          2
3          2
column 2   count
1          2
2          2
3          1
column 3   count
7          3
8          2
3          1

最佳答案

我会这样做:

In [83]: df.drop('id',1).apply(lambda c: c.value_counts().to_dict())
Out[83]:
column1    {3: 2, 2: 2, 1: 1}
column2    {2: 2, 1: 2, 3: 1}
column3          {7: 3, 8: 2}
dtype: object

或者:

In [84]: for c in df.drop('id',1):
    ...:     print(df[c].value_counts())
    ...:
3    2
2    2
1    1
Name: column1, dtype: int64   # <----- column name
2    2
1    2
3    1
Name: column2, dtype: int64
7    3
8    2
Name: column3, dtype: int64

关于python - 如何在 Pandas 中重新格式化 value_counts() 分析以获取大量列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49404061/

相关文章:

python - 如何强制决策树在评估时仅使用整数

python - 将包含日期信息作为对象的列转换为日期时间时出现问题

python - 替换 Pandas 另一行的缺失值

python - 没有聚合的 Pandas 数据透视表形状

通过创建新行替换数据框中一行的值,但保留修改后的原始行

python - 更改 pandas DataFrame 中每个组的第一个元素

python - 将字典写入 json 结果是一个空文件

python - 使用 InceptionV3 的 MNIST 的错误输入形状

python - 当我尝试将单个像素绘制到屏幕上以获得图像时,为什么 pygame 会崩溃

python - 如何将数据帧转换为“从-到”对?