![](/img/trans.png)
[英]Pandas: How to groupby a dataframe and convert the rows to columns and consolidate the rows
[英]Expand pandas dataframe and consolidate columns
我有一個看起來像這樣的數據框:
desc item type1 date1 type2 date2 type3 date3
0 this foo1 A 9/1 B 9/2 C 9/3
1 this foo2 D 9/4 E 9/5 F 9/6
我如何讓它看起來像:
desc item type date
0 this foo1 A 9/1
1 this foo1 B 9/2
2 this foo1 C 9/3
3 this foo2 D 9/4
4 this foo2 E 9/5
5 this foo2 F 9/6
?
檢查wide_to_long
out = pd.wide_to_long(df.reset_index(), ['type','date'], i ='index', j = 'drop').reset_index(drop=True)
out
Out[127]:
type date
0 A 9/1
1 B 9/2
2 C 9/3
對於您更新的問題,相同的概念仍然適用,您只是不需要重置索引,因為item
是唯一的:
pd.wide_to_long(df, stubnames=['type','date'], i='item',j='drop').droplevel(-1).reset_index()
item type date
0 foo1 A 9/1
1 foo2 D 9/4
2 foo1 B 9/2
3 foo2 E 9/5
4 foo1 C 9/3
5 foo2 F 9/6
如果列包含type
或date
您還可以通過使用列表value_vars
將列表傳遞給value_vars
來在兩個數據幀上使用.melt
。 然后,您可以在索引上合並這兩個數據幀:
df = pd.merge(df.melt(id_vars='item', value_vars=[col for col in df.columns if 'type' in col], value_name='type')[['item','type']],
df.melt(id_vars='item', value_vars=[col for col in df.columns if 'date' in col], value_name='date')['date'],
how='left', left_index=True, right_index=True).sort_values('type')
df
Out[1]:
item type date
0 foo1 A 9/1
2 foo1 B 9/2
4 foo1 C 9/3
1 foo2 D 9/4
3 foo2 E 9/5
5 foo2 F 9/6
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.