【问题标题】:Categorical dtype changes after using melt使用 melt 后的分类 dtype 变化
【发布时间】:2018-10-10 23:26:50
【问题描述】:

在回答this question 时,我发现在pandas 数据框上使用melt 后,以前是有序分类数据类型的列变成object。这是预期的行为吗?

注意:不是在寻找解决方案,只是想知道这种行为是否有任何原因,或者它是否不是预期的行为。

示例:

使用以下数据框df

  Cat  L_1  L_2  L_3
0   A    1    2    3
1   B    4    5    6
2   C    7    8    9

df['Cat'] = pd.Categorical(df['Cat'], categories = ['C','A','B'], ordered=True)

# As you can see `Cat` is a category
>>> df.dtypes
Cat    category
L_1       int64
L_2       int64
L_3       int64
dtype: object

melted = df.melt('Cat')

>>> melted
  Cat variable  value
0   A      L_1      1
1   B      L_1      4
2   C      L_1      7
3   A      L_2      2
4   B      L_2      5
5   C      L_2      8
6   A      L_3      3
7   B      L_3      6
8   C      L_3      9

现在,如果我查看Cat,它就变成了一个对象:

>>> melted.dtypes
Cat         object
variable    object
value        int64
dtype: object

这是故意的吗?

【问题讨论】:

  • 超级有趣。我无法想象这是有意为之,您可以考虑在 pandas' GitHub 上提交问题。
  • pandas 在重塑数据时会做一些奇怪的事情。我在transposing 时发现了一些奇怪的行为

标签: python pandas


【解决方案1】:

source 代码中。 0.22.0(我的旧版本)

 for col in id_vars:
        mdata[col] = np.tile(frame.pop(col).values, K)
     mcolumns = id_vars + var_name + [value_name]

这将返回带有np.tile 的数据类型对象。

它已在 0.23.4 中修复(在我更新我的 pandas 之后)

df.melt('Cat')
Out[6]: 
  Cat variable  value
0   A      L_1      1
1   B      L_1      4
2   C      L_1      7
3   A      L_2      2
4   B      L_2      5
5   C      L_2      8
6   A      L_3      3
7   B      L_3      6
8   C      L_3      9
df.melt('Cat').dtypes
Out[7]: 
Cat         category
variable      object
value          int64
dtype: object

更多信息如何修复:

for col in id_vars:
    id_data = frame.pop(col)
    if is_extension_type(id_data): # here will return True , then become concat not np.tile
        id_data = concat([id_data] * K, ignore_index=True)
    else:
        id_data = np.tile(id_data.values, K)
    mdata[col] = id_data

【讨论】:

  • 谢谢!很高兴看到他们修好了!仅供参考,我在使用 pandas '0.21.1' 时发现了这个
猜你喜欢
  • 2022-07-13
  • 1970-01-01
  • 1970-01-01
  • 2015-10-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-11-13
  • 1970-01-01
相关资源
最近更新 更多