【问题标题】:Reshaping a column into rows group-wise using Pandas使用 Pandas 将列按组重新整形为行
【发布时间】:2017-09-26 07:39:04
【问题描述】:

我有一个 df

id    name   value
1      abc     10
1      qwe     23
1      zxc     12
2      sdf     10
2      wed     23
2      abc     12
2      mnb     11

我想将此数据框重塑为:

id    n1    n2    n3    n4
 1    abc   qwe   zxc    0
 2    sdf   wed   abc   mnb

我们可以看到 id=1 有 3 行,id=2 有 4 行。 因此,如果发生这种情况,请替换最后一列 n4=0。

这是测试数据框,可能会发生这样的情况,对于一个 id 也可能有 1-2 行。

这就像我们在 R - dcast 中所做的那样。 我们如何在 pandas 中做到这一点?

【问题讨论】:

    标签: python pandas dataframe group-by pandas-groupby


    【解决方案1】:

    可能过度杀戮

    f, u = pd.factorize(df.id.values)
    b = np.bincount(f)
    n, m = u.size, b.max()
    c = np.arange(f.size) - np.arange(n).repeat(b) * (m - 1)
    
    v = np.zeros((n, m), dtype=object)
    v[f, c] = df.name.values
    
    pd.DataFrame(
        v, pd.Index(u, name='id'),
        ['n{}'.format(i) for i in range(1, m + 1)]
    ).reset_index()
    
       id   n1   n2   n3   n4
    0   1  abc  qwe  zxc    0
    1   2  sdf  wed  abc  mnb
    

    【讨论】:

      【解决方案2】:

      您可以走str 路线并在groupby 之后使用一些正则表达式替换和拆分。

      df.groupby('id').name.apply(lambda x: str(list(x)))\
                .str.replace("[\[\],']", "")\
                .str.split(expand=True).fillna(0)\
                .rename(columns = lambda x: 'n{}'.format(x + 1))
      
           n1   n2   n3   n4
      id                    
      1   abc  qwe  zxc    0
      2   sdf  wed  abc  mnb
      

      【讨论】:

        【解决方案3】:

        您可以使用set_index 和cumcount 来计算新列名称的每组计数,并通过unstack 重塑,最后重命名列:

        df = (df.set_index(['id', df.groupby('id').cumcount()])['name']
               .unstack(fill_value=0)
               .rename(columns = lambda x: 'n{}'.format(x + 1))
               .reset_index())
        print (df)
           id   n1   n2   n3   n4
        0   1  abc  qwe  zxc    0
        1   2  sdf  wed  abc  mnb
        

        DataFrame 构造函数的解决方案,必须在原始数据中没有 NaN 值:

        df1 = df.groupby('id')['name'].apply(list)
        print (df1)
        id
        1         [abc, qwe, zxc]
        2    [sdf, wed, abc, mnb]
        Name: name, dtype: object
        
        df = (pd.DataFrame(df1.values.tolist(), index=df1.index)
                .fillna(0)
                .rename(columns = lambda x: 'n{}'.format(x + 1))
                .reset_index())
        print (df)
           id   n1   n2   n3   n4
        0   1  abc  qwe  zxc    0
        1   2  sdf  wed  abc  mnb
        

        以及GroupBy.apply 和Series 构造函数的解决方案:

        df1 = (df.groupby('id')['name'].apply(lambda x: pd.Series(x.values, index=range(1,len(x)+1)))
                .unstack(fill_value=0)
                .add_prefix('n')
                .reset_index())
        print (df1)
        
           id   n1   n2   n3   n4
        0   1  abc  qwe  zxc    0
        1   2  sdf  wed  abc  mnb
        

        【讨论】:

          【解决方案4】:

          通过使用 dfply 包,可以像 R 的 dcast 那样做。

          # for Python3 only
          pip install dfply
          

          使用dfply 的spread 函数。

          import pandas as pd
          from io import StringIO
          from dfply import *
          
          csv = StringIO("""id,name,value
          1,abc,10
          1,qwe,23
          1,zxc,12
          2,sdf,10
          2,wed,23
          2,abc,12
          2,mnb,11""")
          df = pd.read_csv(csv)
          
          df['sequence'] = df.groupby('id').cumcount()
          df = df[["id", "sequence", "name"]] >> spread(X.sequence, X.name)
          df = df.set_index("id").fillna(0).rename(columns = lambda x: 'n{}'.format(x + 1)).reset_index()
          print(df)
          #    id   n1   n2   n3   n4
          # 0   1  abc  qwe  zxc    0
          # 1   2  sdf  wed  abc  mnb
          

          【讨论】:

            猜你喜欢
            • 2018-11-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-23
            相关资源
            最近更新 更多