【问题标题】:Repeat summary for all columns in Pandas Python对 Pandas Python 中的所有列重复摘要
【发布时间】:2020-07-01 19:57:17
【问题描述】:

我有一个 pandas 数据框,其中包含 100 多个分类列和两个数字列。例如,在下面的数据中,为简单起见,我只包含了四个分类列:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt

df = pd.DataFrame({
    'Gender': ['M','M','F','M','F','M','F','M','F','F'],
    'Class' : ['A','B','B','C','A','C','B','A','A','C'],
    'Class_2': ['A1','B2','B3','C5','B1','C2','B1','B1','C3','D1'],
    'District' : ['N','N','E','S','S','N','N','E','S','S']
})

df['X1'] = np.random.normal(1000, 55, 10)
df['X2'] = np.random.normal(100, 10, 10)

对于每个分类列(即GenderClassClass_2District)我需要做以下总结:

   #Show the distribution of the column, both count and percent
    print((df["Gender"].value_counts(sort=False, normalize=False)))
    print((df["Gender"].value_counts(sort=False, normalize=True))*100)
    
    #Plot the histogram
    plt.figure(figsize=(9, 8))
    plt.hist(df['Gender'], color = 'blue', edgecolor = 'black',
             bins = 30)
    plt.xlabel("Gender")
    plt.ylabel("Count")
    plt.title("Gender distribution")
     

    #Aggregate sum of X1 and X2 by Gender, and find the ratio     
    #ratio by Gender
    var1 = pd.DataFrame(df.groupby('Gender')['X2', 'X1'].agg(['sum']).reset_index())
    var1['ratio'] = var1['X2']/var1['X1']
    print(var1)
     
    var1.plot('Gender', 'ratio', kind='bar',
                 colormap='Paired',
                title=' Ratio by Gender')

【问题讨论】:

  • 好的,你的问题是什么?
  • 对于每个分类列(即 Gender、Class、Class_2 和 District)我需要做我在示例中提出的摘要。

标签: python pandas repeat


【解决方案1】:

首先参数化绘图/统计数据,例如生成函数或过程:

def plot_stats(column):
   #Show the distribution of the column, both count and percent
    print((df[column].value_counts(sort=False, normalize=False)))
    print((df[column].value_counts(sort=False, normalize=True))*100)
    
    #Plot the histogram
    plt.figure(figsize=(9, 8))
    plt.hist(df[column], color = 'blue', edgecolor = 'black',
             bins = 30)
    plt.xlabel(column)
    plt.ylabel("Count")
    plt.title(f"{column} distribution")
     

    #Aggregate sum of X1 and X2 by Gender, and find the ratio     
    #ratio by Gender
    var1 = pd.DataFrame(df.groupby(column)['X2', 'X1'].agg(['sum']).reset_index())
    var1['ratio'] = var1['X2']/var1['X1']
    print(var1)
     
    var1.plot(column, 'ratio', kind='bar',
                 colormap='Paired',
                title= f' Ratio by {column}')
    #add below line to display each plot after printing output:
    plt.show()

然后循环运行:

for col in ['Gender','Class','Class_2','District']:
    plot_stats(col)

在 Jupyter Notebook 环境下工作时,请注意打印输出后显示每个绘图 plt.show() 需要如上函数 plot_stats 所示。

【讨论】:

  • 谢谢@ipj,我看到所有列的所有数字结果都先显示,然后是绘图,是否可以保持顺序?
  • 我在 Spyder 中运行它,所以默认情况下数字输出和绘图是分开的。我猜你是在 Jupyter Notebook 环境中工作?
  • 是的,我在 Jupyter Notebook 工作。有没有办法做到这一点?谢谢!
  • 我已经改进了答案,现在似乎可以按顺序打印输出和绘图了。
猜你喜欢
  • 1970-01-01
  • 2014-07-03
  • 2020-03-26
  • 2016-12-08
  • 2018-10-29
  • 1970-01-01
相关资源
最近更新 更多