【问题标题】:Cartesian product of two categorical variables两个分类变量的笛卡尔积
【发布时间】:2020-11-03 13:42:15
【问题描述】:

让一个 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:我有兴趣在我的 DateFrame 中添加一个 'Sex_Age' 列,其中包含 male_child 等真实数据。

【问题讨论】:

  • 请分享Minimal, Complete, and Verifiable example。另外,请您澄清一下:I don't want this new categorical variable really added to my DataFrame 然后是I want to add this new categorical variable to my DataFrame
  • 我照你说的做了@yatu

标签: python python-3.x pandas matplotlib


【解决方案1】:

我的示例数据框是:

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']))

【讨论】:

    猜你喜欢
    • 2015-06-03
    • 2012-01-03
    • 2017-03-05
    • 2018-11-21
    • 1970-01-01
    • 2015-06-16
    • 2023-03-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多