【问题标题】:Why is pandas.melt messing with my dtypes?为什么 pandas.melt 会弄乱我的 dtypes?
【发布时间】:2020-07-29 00:26:19
【问题描述】:

我有一些枢轴代码因错误而失败

pandas.core.base.DataError:没有要聚合的数字类型

我已将问题追溯到之前致电pandas.melt

以下是熔化前的数据类型:

frame.dtypes
user_id                           Int64
feature                          object
seconds_since_start_assigned      Int32
total                           float32
programme_ids                    object
q1                                Int32
q2                                Int32
q3                                Int32
q4                                Int32
q5                                Int32
q6                                Int32
q7                                Int32
q8                                Int32
q9                                Int32
week                              Int32

现在开始融化

frame1 = pd.melt(
     frame,
     id_vars=['user_id', 'week'],
     value_vars=['q1', 'q2', 'q3', 'q4', 'q5', 'q6', 'q7', 'q8', 'q9'],
     var_name='question',
     value_name='score')
frame1.dtypes
user_id     object
week        object
question    object
score       object

为什么对melt 的调用将Int32 我需要的score 替换为object

【问题讨论】:

    标签: pandas


    【解决方案1】:

    您正在使用可为空的整数数据类型(“Int32”中的大写“I”)。这仍然是一种相当新的数据类型,因此并非所有功能都在那里。即有一个big warning under the Construction section,问题是系列不能推断出一个可为空的整数dtype,尽管也许有一天:

    将来,我们可能会为 Series 提供一个选项来推断可为空的整数 dtype。

    我们自己可以看到这一点。 Series 不会推断出正确的类型,并留下 object 作为唯一可以保存可空整数缺失的容器。数组虽然有效。

    import pandas as pd
    arr = [1, pd._libs.missing.NAType(), 4]
    
    pd.Series(arr)
    #0       1
    #1    <NA>
    #2       4
    #dtype: object   #  <- Did not infer the type :(
    
    pd.array(arr)
    #<IntegerArray>
    #[1, <NA>, 4]
    #Length: 3, dtype: Int64
    

    所以你融化了,得到一个系列,pandas 无法推断 dtype,所以它在融化后被转换为 object。现在,您必须显式转换回“Int32”。

    【讨论】:

      猜你喜欢
      • 2015-12-13
      • 2012-06-18
      • 1970-01-01
      • 2020-08-17
      • 2012-01-23
      • 1970-01-01
      • 2022-01-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多