[英]Pandas Pivot Multiple Date Columns
I have a data frame like this:我有一个这样的数据框:
ColumnA ColumnB 1/1/20 1/2/20 1/3/20
0 Thing1 Item1 4 5 3
1 Thing2 Item1 4 4 5
2 Thing3 Item2 3 4 5
That I'd like to look like this:我想看起来像这样:
But I can't figure out the best method to achieve this via pandas.但我无法找出通过熊猫实现这一目标的最佳方法。 Any help would be much appreciated.任何帮助将非常感激。 Thanks.谢谢。
melt
df.melt(['ColumnA', 'ColumnB'], var_name='Date', value_name='Count')
ColumnA ColumnB Date Count
0 Thing1 Item1 1/1/20 4
1 Thing2 Item1 1/1/20 4
2 Thing3 Item2 1/1/20 3
3 Thing1 Item1 1/2/20 5
4 Thing2 Item1 1/2/20 4
5 Thing3 Item2 1/2/20 4
6 Thing1 Item1 1/3/20 3
7 Thing2 Item1 1/3/20 5
8 Thing3 Item2 1/3/20 5
colname_1, colname_2, *dates = [*df]
data = [
(c1, c2, date, count)
for c1, c2, *counts in zip(*map(df.get, df))
for date, count in zip(dates, counts)
]
pd.DataFrame(data, columns=[colname_1, colname_2, 'Date', 'Count'])
ColumnA ColumnB Date Count
0 Thing1 Item1 1/1/20 4
1 Thing1 Item1 1/2/20 5
2 Thing1 Item1 1/3/20 3
3 Thing2 Item1 1/1/20 4
4 Thing2 Item1 1/2/20 4
5 Thing2 Item1 1/3/20 5
6 Thing3 Item2 1/1/20 3
7 Thing3 Item2 1/2/20 4
8 Thing3 Item2 1/3/20 5
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.