简体   繁体   English

如何将 pipe pandas 分组到 seaborn 分布图?

[英]How to pipe pandas groupby parts to seaborn distplot?

I was learning using.pipe method in pandas and wondering if we can use it to plot the distplot for each group of groupby.我正在学习在 pandas 中使用 pipe 方法,并想知道我们是否可以将它用于 plot 每组 groupby 的分布图。

MWE MWE


import numpy as np
import pandas as pd
import seaborn as sns

# data
np.random.seed(100)
data = {'year': np.random.choice([2016, 2018, 2020], size=400),
        'item': np.random.choice(['Apple', 'Banana', 'Carrot'], size=400),
        'price': np.random.random(size=400)}

df = pd.DataFrame(data)

# distplots
for year in df['year'].unique():
    x = df['price'][df['year'] == year]
    sns.distplot(x, hist=False, rug=True)

Question问题

Can we get the same plot using pandas groupby and without using for loop?我们可以使用 pandas groupby 而不使用 for 循环来获得相同的 plot 吗?

My attempt:我的尝试:

df.groupby('year').pipe(lambda dfx: sns.distplot(dfx['price']))
# TypeError: cannot convert the series to <class 'float'>

# df[['year','price']].groupby('year').pipe(sns.distplot)
# TypeError: float() argument must be a string or a number, not 'DataFrame'

Required output需要 output

Same output as for-loop but using pandas pipe. output 与 for 循环相同,但使用 pandas pipe。 在此处输入图像描述

If you also want labels, you can do following:如果您还想要标签,您可以执行以下操作:

iris = sns.load_dataset('iris')
iris.groupby('species')['sepal_length'].apply(lambda x: sns.distplot(x,
        hist=False, rug=False,label = x.name));
plt.xlabel('sepal_length')
plt.ylabel('kde')

在此处输入图像描述

Not quite pipe , but you can use apply :不太pipe ,但你可以使用apply

df.groupby('year')['price'].apply(sns.distplot, hist=False, rug=True);

Output (which is the same): Output(相同):

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM