Cartesian product of two categorical variables

Viewed 413

Let a DataFrame which have among other two categorical variables one has child young mature old classes and other has male female classes.

How could I have systematically a new column 'Sex_Age' with classes male_child, female_child, male_young, female_young, male_mature, female_mature, male_old, female_old?

In two cases:

  1. I don't want this new categorical variable really added to my DataFrame but only want use it's concept and say, draw jitter plot which have eight bunch of points.

  2. I want to add this new categorical variable to my 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

In case 1: I want jitter plot of 'HairLength' by 8 bunch in one figure corresponding to 8 cases: male_child, female_mature, ... and I'm not interested in the new column.

In case 2: I'm interested in adding a 'Sex_Age' column to my DateFrame with true data such as male_child and so on.

1 Answers

My example DataFrame is:

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

So you can use function get_dummies from pandas:

pd.get_dummies(df, columns=['A', 'B'])

And output will be:


    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

And you can use it to draw, like (but it isn't jitter plot):

pd.get_dummies(df, columns=['A', 'B']).plot(kind='bar')

Or concatenate to your DataFrameWriter with:

df = df.join(pd.get_dummies(df, columns=['A', 'B']))
Related