使用python创建多列的虚拟变量 [英] Create dummy variable of multiple columns with python
问题描述
我正在处理一个包含两列 ID 号的数据框.为了进一步研究,我想对这些 ID 号(带有两个 ID 号)制作一种虚拟变量.但是,我的代码不会合并来自两个数据帧的列.如何合并两个数据框中的列并创建虚拟变量?
I am working with a dataframe containing two columns with ID numbers. For further research I want to make a sort of dummy variables of these ID numbers (with the two ID numbers). My code, however, does not merge the columns from the two dataframes. How can I merge the columns from the two dataframes and create the dummy variables?
数据框
import pandas as pd
import numpy as np
d = {'ID1': [1,2,3], 'ID2': [2,3,4]}
df = pd.DataFrame(data=d)
当前代码
pd.get_dummies(df, prefix = ['ID1', 'ID2'], columns=['ID1', 'ID2'])
期望的输出
p = {'1': [1,0,0], '2': [1,1,0], '3': [0,1,1], '4': [0,0,1]}
df2 = pd.DataFrame(data=p)
df2
推荐答案
如果需要输出中的指标使用max
,如果需要计数值使用sum"http://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.get_dummies.html" rel="nofollow noreferrer">get_dummies
带有另一个参数和将值转换为字符串:
If need indicators in output use max
, if need count values use sum
after get_dummies
with another parameters and casting values to strings:
df = pd.get_dummies(df.astype(str), prefix='', prefix_sep='').max(level=0, axis=1)
#count alternative
#df = pd.get_dummies(df.astype(str), prefix='', prefix_sep='').sum(level=0, axis=1)
print (df)
1 2 3 4
0 1 1 0 0
1 0 1 1 0
2 0 0 1 1
这篇关于使用python创建多列的虚拟变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!