按日期将行旋转到列

发布于 2021-01-29 15:01:52

我有一个名为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:没有要聚合的数字类型

我该怎么办?

关注者
0
被浏览
126
1 个回答
  • 面试哥
    面试哥 2021-01-29
    为面试而生,有面试问题,就找面试哥。

    另一种执行此方法的方法是使用groupyapply(list)然后使用转换列表值到单独的列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
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看