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)
如果您还想要标签,可以执行以下操作:
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)
| 归档时间: |
|
| 查看次数: |
4287 次 |
| 最近记录: |