我和熊猫一起玩是为了适应它,我问自己,在熊猫身上是否可以不需要太多的麻烦就可以使用熔融功能呢?
我正在使用非常著名的titanic.csv数据集。
titanic = pd.read_csv('data/titanic.csv', keep_default_na=True)
titanic.drop(['embarked', 'who', 'adult_male', 'alone', 'parch', 'deck'], \
axis=1, errors="ignore", inplace=True)
titanic_c = titanic.groupby(['class', 'embark_town', 'gender'])['age'] \
.mean().reset_index()
titanic_c

,那么这里有个问题?
我是否能够使用pd.melt将embark_town值添加为类似于此的列?如果是,怎么做?

发布于 2019-06-02 12:07:00
你应该在这里使用df.pivot_table()而不是melt()
m=titanic.pivot_table(index=['pclass','sex'],columns='embark_town',values='age')
print(m)embark_town Cherbourg Queenstown Southampton
pclass sex
1 female 36.052632 33.000000 32.704545
male 40.111111 44.000000 41.897188
2 female 19.142857 30.000000 29.719697
male 25.937500 57.000000 30.875889
3 female 14.062500 22.850000 23.223684
male 25.016800 28.142857 26.574766在您的示例中,您应该将pclass更改为class,将sex更改为gender
https://stackoverflow.com/questions/56414755
复制相似问题