如何将 pandas groupby 部分传输到seaborn distplot?

Pou*_*del 4 python pandas seaborn

我正在学习在 pandas 中使用 .pipe 方法,想知道我们是否可以使用它来绘制每组 groupby 的 distplot。

微量元素


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)
Run Code Online (Sandbox Code Playgroud)

问题

我们可以使用 pandas groupby 而不使用 for 循环得到相同的图吗?

我的尝试:

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'
Run Code Online (Sandbox Code Playgroud)

所需输出

与 for 循环相同的输出,但使用 pandas 管道。 在此输入图像描述

Pou*_*del 5

如果您还想要标签,可以执行以下操作:

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

iris = sns.load_dataset('iris')

#iris.groupby('species')['sepal_length'].apply(lambda x:sns.distplot(x,hist=False, rug=False,label = x.name))

iris.groupby('species')['sepal_length']\
    .apply(lambda x: sns.kdeplot(x, label = x.name))

plt.xlabel('sepal_length')
plt.ylabel('kde')
plt.show()
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述