Python 在几个 DataFrame 列上运行 get_dummies?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24109779/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Running get_dummies on several DataFrame columns?
提问by Emre
How can one idiomatically run a function like get_dummies
, which expects a single column and returns several, on multiple DataFrame columns?
如何get_dummies
在多个 DataFrame 列上惯用地运行像 那样的函数,它需要一个列并返回多个?
采纳答案by bold
With pandas 0.19, you can do that in a single line :
使用pandas 0.19,您可以在一行中完成:
pd.get_dummies(data=df, columns=['A', 'B'])
Columns
specifies where to do the One Hot Encoding.
Columns
指定在何处执行 One Hot Encoding。
>>> df
A B C
0 a c 1
1 b c 2
2 a b 3
>>> pd.get_dummies(data=df, columns=['A', 'B'])
C A_a A_b B_b B_c
0 1 1.0 0.0 0.0 1.0
1 2 0.0 1.0 0.0 1.0
2 3 1.0 0.0 1.0 0.0
回答by joris
Since pandas version 0.15.0, pd.get_dummies
can handle a DataFrame directly (before that, it could only handle a single Series, and see below for the workaround):
从 pandas pd.get_dummies
0.15.0版本开始,可以直接处理 DataFrame(在此之前,它只能处理单个系列,解决方法见下文):
In [1]: df = DataFrame({'A': ['a', 'b', 'a'], 'B': ['c', 'c', 'b'],
...: 'C': [1, 2, 3]})
In [2]: df
Out[2]:
A B C
0 a c 1
1 b c 2
2 a b 3
In [3]: pd.get_dummies(df)
Out[3]:
C A_a A_b B_b B_c
0 1 1 0 0 1
1 2 0 1 0 1
2 3 1 0 1 0
Workaround for pandas < 0.15.0
熊猫 < 0.15.0 的解决方法
You can do it for each column seperate and then concat the results:
您可以对每一列进行单独的操作,然后连接结果:
In [111]: df
Out[111]:
A B
0 a x
1 a y
2 b z
3 b x
4 c x
5 a y
6 b y
7 c z
In [112]: pd.concat([pd.get_dummies(df[col]) for col in df], axis=1, keys=df.columns)
Out[112]:
A B
a b c x y z
0 1 0 0 1 0 0
1 1 0 0 0 1 0
2 0 1 0 0 0 1
3 0 1 0 1 0 0
4 0 0 1 1 0 0
5 1 0 0 0 1 0
6 0 1 0 0 1 0
7 0 0 1 0 0 1
If you don't want the multi-index column, then remove the keys=..
from the concat function call.
如果您不想要多索引列,keys=..
则从 concat 函数调用中删除。
回答by chrisb
Somebody may have something more clever, but here are two approaches. Assuming you have a dataframe named df
with columns 'Name' and 'Year' you want dummies for.
有人可能有更聪明的方法,但这里有两种方法。假设您有一个以df
列“名称”和“年份”命名的数据框,您需要为其设置假人。
First, simply iterating over the columns isn't too bad:
首先,简单地遍历列还不错:
In [93]: for column in ['Name', 'Year']:
...: dummies = pd.get_dummies(df[column])
...: df[dummies.columns] = dummies
Another idea would be to use the patsypackage, which is designed to construct data matrices from R-type formulas.
另一个想法是使用patsy包,该包旨在从 R 型公式构建数据矩阵。
In [94]: patsy.dmatrix(' ~ C(Name) + C(Year)', df, return_type="dataframe")
回答by sapo_cosmico
Unless I don't understand the question, it is supported natively in get_dummiesby passing the columns argument.
除非我不明白这个问题,否则get_dummies通过传递 columns 参数本身就支持它。