融化熊猫DataFrame并将值用作列?

时间:2019-06-02 11:54:32

标签: python pandas

为了适应它,我在和熊猫一起玩,我问自己是否可以在没有使用熔化功能的麻烦的情况下在熊猫里做?

我正在使用非常著名的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

titanic_c at the momet

这是一个问题吗?

我可以使用pd.melt将embark_town值添加为看起来像这样的列吗?如果是,怎么办?

enter image description here

1 个答案:

答案 0 :(得分:2)

IIUC,您应在此处使用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

相关问题