大熊猫数据转换

介子

如何从这种形式获取数据(数据的长表示形式):

import pandas as pd
df = pd.DataFrame({
    'c0': ['A','A','B'],
    'c1': ['b','c','d'],
    'c2': [1, 3,4]})

print(df)

出:

   c0 c1  c2
0  A  b   1
2  A  c   3
3  B  d   4

这种形式:

   c0 c1  c2
0  A  b   1
2  A  c   3
3  A  d   NaN
4  B  b   NaN
5  B  c   NaN
6  B  d   4

从长到宽到长的转型是这样做的唯一方法吗?

海盗

方法1
unstackstack

df.set_index(['c0', 'c1']).unstack().stack(dropna=False).reset_index()

在此处输入图片说明

方法2
reindex与产品

df.set_index(['c0', 'c1']).reindex(
    pd.MultiIndex.from_product([df.c0.unique(), df.c1.unique()], names=['c0', 'c1'])
).reset_index()

在此处输入图片说明

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章