【问题标题】:Python Pandas Unstacking Unique Column Values to Columns Of Their OwnPython Pandas 将唯一的列值拆分为自己的列
【发布时间】:2016-06-30 15:48:41
【问题描述】:
df = pd.DataFrame({'Col1': ['label1', 'label1', 'label2', 'label2',
          'label3', 'label3', 'label4'],
 'Col2': ['a', 'd', 'b', 'e', 'c', 'f', 'q']}, columns=['Col1', 'Col2'])

看起来像这样

     Col1 Col2
0  label1    a
1  label1    d
2  label2    b
3  label2    e
4  label3    c
5  label3    f
6  label4    q

对于Col1 中的唯一值,我想将列的唯一值转换为列。从某种意义上说,我试图将Col1 值“取消堆叠”为列标题,而行值将是Col2 中的值。我的主要问题是我没有计算任何数字数据 - 都是文本 - 我只是想重塑结构。

这是想要的结果:

  label1 label2 label3 label4
0      a      b      c      q
1      d      e      f    NaN

我试过了:stackunstackpd.meltpivot_tablepivot

这几乎可以让我到达那里,但并不完全,而且似乎不是很简洁:

df.groupby('Col1').apply(lambda x: x['Col2'].values).to_frame().T

Col1  label1  label2  label3 label4
0     [a, d]  [b, e]  [c, f]    [q]

This question shows how to do it with a pivot table.. 但就我而言,数字索引不是我关心的东西。

This question shows how to also do it with a pivot table.. 使用 aggfunc first' '.join 但返回 CSV 而不是相应行上的值。

【问题讨论】:

    标签: python pandas text grouping


    【解决方案1】:

    您可以使用cumcount 为新的index 创建列,然后使用pivot_table 聚合join

    df['g'] = df.groupby('Col1')['Col1'].cumcount()
    
    print (df.pivot_table(index='g', columns='Col1', values='Col2', aggfunc=''.join))
    Col1 label1 label2 label3 label4
    g                               
    0         a      b      c      q
    1         d      e      f   None
    

    感谢您的评论Jeff L.

    df['g'] = df.groupby('Col1')['Col1'].cumcount()
    
    print (df.pivot(index='g', columns='Col1', values='Col2'))
    Col1 label1 label2 label3 label4
    g                               
    0         a      b      c      q
    1         d      e      f   None
    

    或者:

    print (pd.pivot(index=df.groupby('Col1')['Col1'].cumcount(),
                    columns=df['Col1'], 
                    values=df['Col2']))
    
    Col1 label1 label2 label3 label4
    0         a      b      c      q
    1         d      e      f   None
    

    【讨论】:

    • 您也可以将此处的pivot_table 替换为df.pivot(index='g', columns='Col1', values='Col2'),并以略短的行获得相同的结果。
    【解决方案2】:

    使用set_indexunstack,你可以这样做

    In [17]: df.set_index([df.groupby('Col1')['Col1'].cumcount(), 'Col1'])['Col2'].unstack()
    Out[17]:
    Col1 label1 label2 label3 label4
    0         a      b      c      q
    1         d      e      f   None
    

    详情

    In [18]: df
    Out[18]:
         Col1 Col2
    0  label1    a
    1  label1    d
    2  label2    b
    3  label2    e
    4  label3    c
    5  label3    f
    6  label4    q
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-09
      • 1970-01-01
      • 2020-10-01
      • 2018-07-27
      • 2020-02-10
      • 1970-01-01
      相关资源
      最近更新 更多