【问题标题】:Pandas get_dummies to output dtype integer/bool instead of floatPandas get_dummies 输出 dtype integer/bool 而不是 float
【发布时间】:2019-12-13 01:38:44
【问题描述】:

我想知道是否可以要求pandas中的get_dummies函数输出dtype比默认float64轻的dummy数据帧。

因此,对于具有分类列的示例数据框:

In []: df = pd.DataFrame([(blue,wood),(blue,metal),(red,wood)],
                         columns=['C1','C2'])
In []: df
Out[]:
    C1      C2
0   blue    wood
1   blue    metal
2   red     wood

得到假人后的样子:

In []: df = pd.get_dummies(df)
In []: df    
Out[]:
 C1_blue    C1_red  C2_metal    C2_wood
0   1   0   0   1
1   1   0   1   0
2   0   1   0   1

这很好。但是,默认情况下 1 和 0 是 float64:

In []: df.dtypes
Out[]: 
C1_blue     float64
C1_red      float64
C2_metal    float64
C2_wood     float64
dtype: object

我知道之后我可以使用 astype 更改 dtype:

In []: df = pd.get_dummies(df).astype(np.int8)

但我不想在内存中有浮点数的数据帧,因为我正在处理一个大数据帧(来自约 5Gb 的 csv)。我想将假人直接作为整数。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    有一个未解决的问题 w.r.t.这个,看这里:https://github.com/pydata/pandas/issues/8725

    【讨论】:

    • 谢谢杰夫!问题解决后,请在此处告知我们(如果您记得的话)。顺便说一句,pd.Categorical 并不能解决这个特定问题,但它可能对进行 one-hot 编码有很大帮助。
    • 关闭,0.19.0实现
    【解决方案2】:

    浮动问题现已解决。从 pandas 0.19 版开始,pd.get_dummies 函数将虚拟编码的列返回为小整数。

    见:http://pandas.pydata.org/pandas-docs/stable/whatsnew.html#get-dummies-now-returns-integer-dtypes

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-07-07
      • 1970-01-01
      • 1970-01-01
      • 2023-03-28
      • 2012-10-20
      • 1970-01-01
      • 1970-01-01
      • 2012-09-19
      相关资源
      最近更新 更多