Python 基于选定列透视数据帧
dataframe如何处理Python 基于选定列透视数据帧,python,pandas,Python,Pandas,dataframe如何处理 df = pd.DataFrame({'car':['BMW','BMW','VW','VW'],'color':['red','blue','red','blue'],'count':[1,2,4,8]}) df car color count 0 BMW red 1 1 BMW blue 2 2 VW red 4 3 VW blue 8 转化为 car
df = pd.DataFrame({'car':['BMW','BMW','VW','VW'],'color':['red','blue','red','blue'],'count':[1,2,4,8]})
df
car color count
0 BMW red 1
1 BMW blue 2
2 VW red 4
3 VW blue 8
转化为
car red blue
0 BMW 1 2
1 VW 4 8
?您可以使用:
如果有多行具有相同的(汽车、颜色)组合,则使用指定希望如何聚合计数
s:
In [7]: df.pivot_table(index='car', columns='color', values='count', aggfunc='sum').reset_index()
Out[7]:
color car blue red
0 BMW 2 1
1 VW 8 4
如果要删除颜色标记,请添加
df.columns.name=None
In [7]: df.pivot_table(index='car', columns='color', values='count', aggfunc='sum').reset_index()
Out[7]:
color car blue red
0 BMW 2 1
1 VW 8 4