我还有另一项重塑熊猫数据框的具体任务。
我有相同的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有一种颜色)。也就是说,它将保留第二位,并且应该仅创建两种新闻颜色(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的出现顺序无关紧要。
有人可以帮助我吗?预先感谢
答案 0 :(得分:3)
这是使用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
答案 1 :(得分:1)
您可以使用此:
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