【问题标题】:Create a function as input one of a pandas column (variable) to create plots创建一个函数作为 pandas 列(变量)的输入之一以创建绘图
【发布时间】:2020-09-29 17:25:59
【问题描述】:

我有一个包含多列和变量的数据框。 我想创建一个函数以应用于数据帧的某些变量,以创建一些表示均值、中位数和众数的分布图。 我找到了一个很棒的代码,你会在后面看到。

我的问题是我想自动创建显示图,而不是每次我想在另一个变量上创建图时都复制粘贴它,但我不知道该怎么做。

这是代码(我想轻松更改变量“fat_100g”):

f, (ax_box, ax_hist) = plt.subplots(2, sharex=True, gridspec_kw= {"height_ratios": (0.2, 1)})
mean=df['fat_100g'].mean()
median=df['fat_100g'].median()
mode=df['fat_100g'].mode().to_numpy()[0]

sns.boxplot(df["fat_100g"], ax=ax_box)
ax_box.axvline(mean, color='r', linestyle='--')
ax_box.axvline(median, color='g', linestyle='-')
ax_box.axvline(mode, color='b', linestyle='-')

sns.distplot(df["fat_100g"], ax=ax_hist)
ax_hist.axvline(mean, color='r', linestyle='--')
ax_hist.axvline(median, color='g', linestyle='-')
ax_hist.axvline(mode, color='b', linestyle='-')

plt.legend({'Mean':mean,'Median':median,'Mode':mode})

ax_box.set(xlabel='')
plt.show()

【问题讨论】:

    标签: python pandas function dataframe plot


    【解决方案1】:

    您可以创建一个变量,将其命名为 key=(任意您想要的),然后使用:

    mean=df[key].mean()
    

    如果您想遍历所有这些:

    for key in list(df.columns):
        ##Do the plotting code; pay attention to not overwriting axes if you want to do this, maybe make ax a list and loop through the list using ax[ind] and add to the ind every loop?
    

    【讨论】:

    • 感谢您的帮助:)
    猜你喜欢
    • 1970-01-01
    • 2013-10-02
    • 1970-01-01
    • 1970-01-01
    • 2018-05-29
    • 2013-11-15
    • 2021-06-04
    • 2012-01-14
    • 1970-01-01
    相关资源
    最近更新 更多