【问题标题】:Pandas groupby to create new dataframe with values as columnsPandas groupby 以值作为列创建新数据框
【发布时间】:2018-05-05 22:17:12
【问题描述】:

我想将 Python 中的 Date 数据重塑为数据框。

必填:

有熊猫功能吗?

【问题讨论】:

    标签: python pandas dataframe pivot reshape


    【解决方案1】:

    使用 cumcount 创建附加密钥,然后我们执行 pivot ,来自 jpp 的数据

    df.assign(key=df.groupby('Col1').cumcount()).pivot('key','Col1','Col2')
    Out[29]: 
    Col1    A    B    C
    key                
    0     1.0  4.0  6.0
    1     2.0  5.0  7.0
    2     3.0  NaN  8.0
    

    【讨论】:

      【解决方案2】:

      一种方法是在从键列中的唯一值派生的系列上使用pandas.concat

      这是一个最小的例子。

      import pandas as pd
      
      df = pd.DataFrame({'Col1': ['A', 'A', 'A', 'B', 'B', 'C', 'C', 'C'],
                         'Col2': [1, 2, 3, 4, 5, 6, 7, 8]})
      
      res = pd.concat({k: df.loc[df['Col1']==k, 'Col2'].reset_index(drop=True)
                       for k in df['Col1'].unique()}, axis=1)
      
      print(res)
      
         A    B  C
      0  1  4.0  6
      1  2  5.0  7
      2  3  NaN  8
      

      【讨论】:

      • 给了你一个 ++,因为我不相信没有解释的 dvs,但你可以通过迭代 groupby 来更轻松地做到这一点......
      • @cᴏʟᴅsᴘᴇᴇᴅ,谢谢 - 也做 UV Wen 的解决方案:)。
      猜你喜欢
      • 2022-10-13
      • 1970-01-01
      • 2021-10-09
      • 1970-01-01
      • 2021-06-11
      • 2016-09-21
      • 2018-12-03
      • 1970-01-01
      • 2017-10-01
      相关资源
      最近更新 更多