我有一个具有三个不同种类的数据框“ iris”,如何使用 所有不同的种类作为列名,隔片长度作为值?
设置:
import numpy as np
import pandas as pd
df = sns.load_dataset('iris')
print(df.head())
sepal_length sepal_width petal_length petal_width species
0 5.1 3.5 1.4 0.2 setosa
1 4.9 3.0 1.4 0.2 setosa
2 4.7 3.2 1.3 0.2 setosa
3 4.6 3.1 1.5 0.2 setosa
4 5.0 3.6 1.4 0.2 setosa
这是一个漫长而困难的方法,我正在寻找一些groupby方法,该方法可能使用链在单个操作中完成此操作。
seto = df.loc[df['species']=='setosa','sepal_length']
ver = df.loc[df['species']=='versicolor','sepal_length']
vir = df.loc[df['species']=='virginica','sepal_length']
ans = pd.DataFrame({'setosa': seto.values,'versicolor':ver.values,'virginica':vir.values})
print(ans.head())
df.groupby('species')['spepal_length'].SOMETHING.SOMETHING
setosa versicolor virginica
0 5.1 7.0 6.3
1 4.9 6.4 5.8
2 4.7 6.9 7.1
3 4.6 5.5 6.3
4 5.0 6.5 6.5
答案 0 :(得分:1)
这是pivot_table
:
df.pivot_table(index=df.groupby('species').cumcount(),
columns='species',
values='sepal_length',
aggfunc='first'
)
输出(头):
species setosa versicolor virginica
0 5.1 7.0 6.3
1 4.9 6.4 5.8
2 4.7 6.9 7.1
3 4.6 5.5 6.3
4 5.0 6.5 6.5
5 5.4 5.7 7.6