【问题标题】:Reshape panda dataframe in a specific way Part 2以特定方式重塑 pandas 数据框第 2 部分
【发布时间】:2020-02-24 15:21:56
【问题描述】:

我还有另一项特定任务是重塑熊猫数据框。

我有相同的python代码

import pandas as pd

data = {'ID': [123, 123,124], 'Method': ['angular', 'angular','angular'], 'Colour': ['red', 'blue','Noir'], 'Size': [20, 30,10] }

df = pd.DataFrame (data, columns = ['ID','Method','Colour','Size'])
df

ID  Method  Colour  Size
123 angular red     20
123 angular blue    30
124 angular Noir    10

用下面的代码

resul = df.reset_index().set_index(['ID', 'Method', 'index']
                                   ).unstack().reset_index() #.groupby(['ID','Method'])

resul.columns = [i if j == '' else i + '_' + str(j)
                 for i, j in resul.columns.tolist()]
resul

我得到以下结果

    ID  Method  Colour_0    Colour_1    Colour_2    Size_0  Size_1  Size_2
0   123 angular   red         blue        NaN         20.0    30.0   NaN
1   124 angular   NaN         NaN         Noir        NaN     NaN    10.0

但是想要的是代码计算每个ID有多少颜色然后保持最大值(与df相关,ID = 123有两种颜色,ID = 124有一种颜色)。也就是说,它将保留数字 2,并且应该只创建两种新闻颜色(coulour_0 和 colour_1)而不是 3。对于列 Size 也是如此。它应该只有两列。结果表应如下所示

    ID  Method  Colour_0    Colour_1    Size_0  Size_1  
0   123 angular   red         blue        20.0    30.0  
1   124 angular   Noir        NaN          10.0    NaN

两者的 NaN 出现的顺序无关紧要。

有人可以帮帮我吗?提前致谢

【问题讨论】:

  • 建议您upvote 有帮助的解决方案和accept 其中之一。

标签: python pandas dataframe reshape


【解决方案1】:

这是使用pivot_table 的一种方式。请注意,我们需要创建旋转数据框的列,要对它们进行编号,我们可以使用GroupBy.cumcount

g = df.groupby('ID').Colour.cumcount()
out = df.pivot_table(index=['ID', 'Method'], 
                     columns=g,
                     values=['Colour', 'Size'],
                     aggfunc='first')

# combine both levels in the MultiIndex column into one
out.columns = ['_'.join(map(str, t)) for t in out.columns]
print(out.reset_index())

   ID   Method  Colour_0 Colour_1  Size_0  Size_1
0  123  angular      red     blue    20.0    30.0
1  124  angular     Noir      NaN    10.0     NaN

【讨论】:

【解决方案2】:

你可以用这个:

resul = df.set_index(['ID', 'Method', df.groupby('ID')['Colour'].cumcount()]).unstack()
resul.columns = [f'{i}_{j}' for i, j in resul.columns]
resul = resul.reset_index()
print(resul)

输出:

    ID   Method Colour_0 Colour_1  Size_0  Size_1
0  123  angular      red     blue    20.0    30.0
1  124  angular     Noir      NaN    10.0     NaN

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-10
    • 2020-04-19
    • 1970-01-01
    相关资源
    最近更新 更多