首页 > 解决方案 > 两个分类变量的笛卡尔积

问题描述

让一个 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

在两种情况下:

  1. 我不希望这个新的分类变量真正添加到我的 DataFrame 中,而只想使用它的概念并说,绘制 jitter plot有八个点。

  2. 我想将这个新的分类变量添加到我的 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'列中添加一个DateFrame包含真实数据的列,例如male_child等等。

标签: pythonpython-3.xpandasmatplotlib

解决方案


我的示例数据框是:

df = pd.DataFrame({'A':['male', 'female', 'male'], 'B':['one', 'two', 'three']})

所以你可以使用来自 pandas 的函数 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']))

推荐阅读