首页 > 解决方案 > 熊猫数据框列表的箱线图

问题描述

我有下一个数据框列表

列表 = [df1, df2, df3, df4]

所有的dfs都具有相同的结构

df = [col1, col2, col3]

我想在每个 df 中制作一个具有相同列的箱线图,但我不能,我正在尝试:

for df in dfs:
    df.boxplot(column='col1', subplots=True)

解决方案是:

new_df = pd.concat(list, axis=1)
for column in new_df:
    df.boxplot(['col1'])

标签: pandasboxplot

解决方案


您可以将所有 dfs 组合成一个更大的数据框(按行连接),然后使用内置的箱线图方法创建所有列的箱线图,因为默认行为是为每一列创建箱线图。

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

np.random.seed(42)
df1 = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=['col1','col2','col3'])
df2 = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=['col1','col2','col3'])
df3 = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=['col1','col2','col3'])
df4 = pd.DataFrame(np.random.randint(0,100,size=(100, 3)), columns=['col1','col2','col3'])

dfs = [df1, df2, df3, df4]

## this will create a big dataframe composed of all the dfs
all_data = pd.concat(dfs, axis=1)

## this creates one boxplot for the first dataframe, loop through this
boxplot = all_data.iloc[:,0:3].boxplot()
plt.show()

在此处输入图像描述


推荐阅读