让一个DataFrame具有其他两个类别变量,其中一个具有child young mature old
类,另一个具有male female
类。
我如何系统地新建一个类为'Sex_Age'
的新列male_child, female_child, male_young, female_young, male_mature, female_mature, male_old, female_old
?
在两种情况下:
我不希望这个新的类别变量真正添加到我的DataFrame中,而是只想使用它的概念并说画jitter plot
,它有八点。
我想将此新的类别变量添加到我的DataFrame中。
import pandas as pd
df = pd.DataFrame({'Sex':['male', 'female',\
'male', 'male', 'male', 'female', 'male',\
'male', 'female'], 'Age':['child', 'old', 'mature',\
'young', 'young', 'mature', 'child', 'child', 'child'],
'HairLength':[2,30,8,15,9,35,3,5,6]})
df
在情况1中:我希望将jitter plot
中的'HairLength'
乘以8束,一幅数字对应8种情况:male_child, female_mature, ...
,我对此不感兴趣新列。
在情况2中:我有兴趣向'Sex_Age'
的{{1}}列添加真实数据,例如DateFrame
等。 >
答案 0 :(得分:0)
我的示例DataFrame是:
df = pd.DataFrame({'A':['male', 'female', 'male'], 'B':['one', 'two', 'three']})
因此您可以使用熊猫函数get_dummies:
pd.get_dummies(df, columns=['A', 'B'])
输出将是:
A_female A_male B_one B_three B_two
0 0 1 1 0 0
1 1 0 0 0 1
2 0 1 0 1 0
您可以使用它进行绘制,例如(但它不是抖动图):
pd.get_dummies(df, columns=['A', 'B']).plot(kind='bar')
或通过以下方式连接到您的DataFrameWriter:
df = df.join(pd.get_dummies(df, columns=['A', 'B']))