按日期将行旋转到列 [英] Pivot rows to columns by date pandas
本文介绍了按日期将行旋转到列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个名为df的Pandas DataFrame,如下所示:
I have a Pandas DataFrame called df that looks like this:
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:没有要聚合的数字类型
pandas.core.base.DataError: No numeric types to aggregate
我该怎么办?
推荐答案
另一种方法是使用groupy
,apply(list)
,然后用Series.values.tolist()
Another way to do this is with groupy
, apply(list)
and after that converting the list values to seperate columns with Series.values.tolist()
# Groupby and get the values in a list per unique value of the Date column
df = df.groupby('Date').String.apply(list).reset_index()
Date String
0 2016-06-30 [d, e, f]
1 2016-08-01 [a, b, c]
# Convert the values from the list to seperate columns and after that drop the String column
df[['Column1', 'Column2', 'Column3']] = pd.DataFrame(df.String.values.tolist(), index=df.index)
df.drop('String', axis=1, inplace=True)
Date Column1 Column2 Column3
0 2016-06-30 d e f
1 2016-08-01 a b c
这篇关于按日期将行旋转到列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文