扩大熊猫数据框架

时间:2017-08-10 11:31:56

标签: python pandas dataframe

我的数据如下:

Box,Code
Green,1221
Green,8391
Red,3709
Red,2911
Blue,9820
Blue,4530

使用pandas数据框,我想知道是否可以输出这样的内容:

Box,Code1,Code2
Green,1221,8391
Red,3709,2911
Blue,9820,4530

我的数据每行的行数始终相等。

我已经在熊猫中试验过枢轴和交叉工具(以及堆叠和堆叠),但是没有发现任何让我进入“扩大”的东西。结果我正在寻找。

1 个答案:

答案 0 :(得分:4)

您可以list使用DataFrame,然后使用a = df.groupby('Box')['Code'].apply(list) df = pd.DataFrame(a.values.tolist(), index=a.index).add_prefix('Code').reset_index() print (df) Box Code0 Code1 0 Blue 9820 4530 1 Green 1221 8391 2 Red 3709 2911 构造函数:

Series

groupbycumcountg = df.groupby('Box').cumcount() df = pd.pivot(index=df['Box'], columns=g, values=df['Code']).add_prefix('Code').reset_index() print (df) Box Code0 Code1 0 Blue 9820 4530 1 Green 1221 8391 2 Red 3709 2911 pandas.pivot

df['g'] = df.groupby('Box').cumcount()
df = df.set_index(['Box', 'g'])['Code'].unstack().add_prefix('Code').reset_index()
print (df)
g    Box  Code0  Code1
0   Blue   9820   4530
1  Green   1221   8391
2    Red   3709   2911

unstack类似的解决方案:

System.getProperty("user.dir")