python - 两个分类变量的笛卡尔积
问题描述
让一个 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'
列中添加一个DateFrame
包含真实数据的列,例如male_child
等等。
解决方案
我的示例数据框是:
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']))
推荐阅读
- java - 拼图 65-java 益智游戏。int 溢出可能发生在涉及负数减法、int.Max_Value 等的计算中你如何避免它?
- python - 传递查询参数,但出现需要查询参数的错误
- node.js - Node js 和 Reactjs 中的实时摄像头流式传输
- java - 是否应该为重复访问的特定索引处的数组元素引入局部变量?
- php - 当管理员在我的视图中批准时,我应该如何显示数据
- java - QName 的创建采用默认命名空间前缀而不是提供的参数
- jenkins - 我如何启动命令提示符并在 Jenkins 作为服务中运行命令?
- applescript - 遍历列,将每个单元格的内容减去一定数量,并将结果存储在同一个单元格中
- reactjs - 为什么 componentDidMount 在没有触发 componentDidUpdate 的 HOC 中触发?
- linux - 没有名为 _dbus_bindings 的模块 fedora 34