代码之家  ›  专栏  ›  技术社区  ›  Dmitriy Kisil

在pandas数据框中创建具有特定值的列

  •  1
  • Dmitriy Kisil  · 技术社区  · 8 年前

    我有带列的数据框 author hour (作者发表主题时)和 number_of_topics

      author hour number_of_topics
    0      A  h01                1
    1      B  h02                4
    2      B  h04                2
    3      C  h04                6
    4      A  h05                8
    5      C  h05                3
    

    我的目标是创建六个列(前六个小时)并用许多主题填充它们。我试着用 df.groupby 但没有成功。

      author h01 h02 h03 h04 h05 h06
    0      A   1   0   0   0   8   0
    1      B   0   4   0   2   0   0
    2      C   0   0   0   6   3   0 
    

    创建数据帧的代码:

    import pandas as pd
    df = pd.DataFrame({"author":["A","B", "B","C","A","C"],
                       "hour":["h01","h02","h04","h04","h05","h05"],
                       "number_of_topics":["1","4","2","6","8","3"]})
    print(df)
    
    2 回复  |  直到 8 年前
        1
  •  1
  •   jezrael    8 年前

    使用 pivot reindex 对于添加错误列:

    cols = ['h{:02d}'.format(x) for x in range(1, 7)]
    df = (df.pivot('author','hour','number_of_topics')
            .fillna(0)
            .reindex(columns=cols, fill_value=0)
            .reset_index()
            .rename_axis(None, axis=1))
    print (df)
      author h01 h02  h03 h04 h05  h06
    0      A   1   0    0   0   8    0
    1      B   0   4    0   2   0    0
    2      C   0   0    0   6   3    0
    

    或者 set_index 具有 unstack :

    cols = ['h{:02d}'.format(x) for x in range(1, 7)]
    df = (df.set_index(['author','hour'])['number_of_topics']
            .unstack(fill_value=0)
            .reindex(columns=cols, fill_value=0)
            .reset_index()
            .rename_axis(None, axis=1))
    print (df)
      author h01 h02  h03 h04 h05  h06
    0      A   1   0    0   0   8    0
    1      B   0   4    0   2   0    0
    2      C   0   0    0   6   3    0
    
        2
  •  0
  •   ysearka    8 年前

    你要找的东西可以通过 pivot

    df.pivot(index = 'author',columns = 'hour',values = 'number_of_topics').fillna(0)
    
    hour    h01     h02     h04     h05
    author              
    A       1       0       0       8
    B       0       4       2       0
    C       0       0       6       3