我有一个名为 df 的 Pandas DataFrame,如下所示:
Date String
2016-08-01 a
2016-08-01 b
2016-08-01 c
2016-06-30 d
2016-06-30 e
2016-06-30 f
我正在努力获得:
Date Column1 Column2 Column3
2016-08-01 a b c
2016-06-30 d e f
我尝试使用:
df = pd.pivot_table(df, index='Date')
或:
df.pivot_table(index=['Date'], values="News")
但我不断收到:
pandas.core.base.DataError: No numeric types to aggregate
我该怎么办?
请您参考如下方法:
使用 groupby 和 cumcount 获取日期的重复计数,然后使用 pivot:
(df.assign(Count=df.groupby('Date').cumcount()+1)
.pivot('Date', 'Count', 'String')
.add_prefix('Column'))
Count Column1 Column2 Column3
Date
2016-06-30 d e f
2016-08-01 a b c
或者,set_index 和unstack:
(df.set_index(['Date', df.groupby('Date').cumcount()+1])['String']
.unstack()
.add_prefix('Column'))
Column1 Column2 Column3
Date
2016-06-30 d e f
2016-08-01 a b c
