Python Pandas 序列 if else 箱线图

Python Pandas Series if else box plot

我有很多字典格式的数据,我正在尝试使用 pandas 打印基于 IF ELSE 语句的字符串。对于我的示例,我将在 dict 中编写一些数据并转换为 Pandas:

df = pd.DataFrame(dict(a=[1.5,2.8,9.3],b=[7.2,3.3,4.9],c=[13.1,4.9,15.9],d=[1.1,1.9,2.9]))

df

这个returns:

    a   b   c   d
0   1.5 7.2 13.1 1.1
1   2.8 3.3 4.9 1.9
2   9.3 4.9 15.9 2.9

我的 IF ELSE 语句:

for col in df.columns:
    if (df[col] < 4).any():
        print('Zone %s does not make setpoint' % col)
    else:
        print('Zone %s is Normal' % col)

Returns:

Zone a does not make setpoint
Zone b does not make setpoint
Zone c is Normal
Zone d does not make setpoint

但现在我想添加一个额外的内容来创建一个箱形图,其中我没有设定设定点,并且还对设定设定点的数据框进行平均。我知道这是pandas系列,但是pandas.Series.plot.box()可以用吗?

这是我在带有 df.apply(lamba x:) 的函数中使用的 IF ELSE 语句,我一直在尝试让箱线图在 pandas 系列中工作......任何建议都是非常感谢!

import matplotlib.pyplot as plt

def _print(x):
    if (x < 4).any():
        print('Zone %s does not make setpoint' % x.name)
        df.boxplot()
        plt.show()
    else:
        print('Zone %s is Normal' % x.name)
        print('The average is %s' % x.mean())

我在调用时遇到错误 df.apply(lambda x: _print(x))

module 'matplotlib' has no attribute 'show'

我真的不知道这是否是您要找的,但是...您在问:

I want to add in an extra to create a box plot

您正在尝试使用... df.Series.plot.box(),输出错误 AttributeError: 'DataFrame' object has no attribute 'Series'

尝试使用 df.boxplot(),然后在每次 plt.show() 调用时显示...

当然可以像 df['a'].plot.box() 一样调用 pandas.Series.plot.box() 来获取列 a 的箱线图。

为了符合你的问题,我会这样做:

def _print(x):
    if (x < 4).any():
        print('Zone %s does not make setpoint' % x.name)
        df[x.name].plot.box() #call x.name to retrieve the column name
        plt.show()
        print(df[x.name].describe())
    else:
        print('Zone %s is Normal' % x.name)
        print('The average is %s' % x.mean())
    print('---')

df.apply(lambda x: _print(x))

下面显示了 zone Bzone C 的输出摘录。

请注意,您可以添加 .describe() 以获取箱线图和其他统计信息描述(参见 documentation)。

尽管如此,根据提出的解决方案

,我会以不同的方式处理问题

另一种解决方案

您可以过滤您的数据帧以拆分或不拆分为设定点:

s = df.apply(lambda x: not (x < 4).any())

然后在没有达到设定点的那个上绘制方框。
如果变化不是太大,并且没有那么多区域,请将所有内容绘制在图中:

df[s[~s].index].boxplot()
plt.show()

或者将它们分开:

for col in s[~s].index:
    df[col].plot.box()
    plt.show()

在这两种情况下,在 dataframe:

中获取统计信息
statdf = df[s[~s].index].describe()
print(statdf)

              a         b         d
count  3.000000  3.000000  3.000000
mean   4.533333  5.133333  1.966667
std    4.178915  1.960442  0.901850
min    1.500000  3.300000  1.100000
25%    2.150000  4.100000  1.500000
50%    2.800000  4.900000  1.900000
75%    6.050000  6.050000  2.400000
max    9.300000  7.200000  2.900000

通过这种方式,您可以使用 statdf.loc['mean'].

获取统计信息(例如,说“mean”)

如果您想打印达到设定点的均值:

print(df[s[s].index].mean())

c    11.3
Name: mean, dtype: float64