【问题标题】:Pivot rows to columns by date pandas按日期将行透视到列 pandas
【发布时间】:2019-06-27 17:43:21
【问题描述】:

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

我该怎么办?

【问题讨论】:

    标签: python pandas date pivot pivot-table


    【解决方案1】:

    另一种方法是使用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
    

    【讨论】:

      【解决方案2】:

      使用groupbycumcount 获取日期的重复计数,然后使用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_indexunstack

      (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
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-06-10
        • 2015-11-25
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-03-14
        • 1970-01-01
        相关资源
        最近更新 更多