Python 使用melt后,分类数据类型发生变化
在回答时,我发现在熊猫数据帧上使用Python 使用melt后,分类数据类型发生变化,python,pandas,Python,Pandas,在回答时,我发现在熊猫数据帧上使用melt后,以前是有序分类数据类型的列将变成对象。这是故意的行为吗 注意:不是寻找解决方案,只是想知道这种行为是否有任何原因,或者它是否不是预期的行为 示例: 使用以下数据帧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','
melt
后,以前是有序分类数据类型的列将变成对象。这是故意的行为吗
注意:不是寻找解决方案,只是想知道这种行为是否有任何原因,或者它是否不是预期的行为
示例:
使用以下数据帧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
现在,如果我看一下猫,它变成了一个对象:
>>> melted.dtypes
Cat object
variable object
value int64
dtype: object
这是故意的吗?在代码中。0.22.0(我的旧版本)
它将返回带有np.tile
的数据类型对象
它已在0.23.4中修复(在我更新我的pandas
之后)
有关如何修复的详细信息:
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
非常有趣。我无法想象这是故意的,你可能会考虑提交一个关于<代码>熊猫> <代码> Github.熊猫在重塑数据时做了一些奇怪的事情。我在感谢时发现了一些奇怪的行为!很高兴看到他们修好了!仅供参考,我是在使用pandas
'0.21.1'时发现的
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