转换Pandas DataFrame,将行值添加为列标题

时间:2017-05-16 10:26:27

标签: python pandas dataframe

我有一个像这样的pandas数据框:

COMMIT_ID | FILE_NAME     | COMMITTER | CHANGE TYPE
-------------------------------------------------------------
  1       |  package.json | A         | MODIFY
  2       |  main.js      | B         | ADD
  2       |  class.java   | B         | DELETE

我想将文件名的行值作为列标题,将changetype作为值。

COMMIT_ID | package.json | main.js     | class.java     | COMMITTER
-----------------------------------------------------------------------------
  1       |  MODIFY      |  NONE       |  NONE          | A         
  2       |  NONE        |  ADD        |  DELETE        | B      

我尝试过pandas.pivot_table,但并不是很成功。有机会轻松做到这一点吗?

1 个答案:

答案 0 :(得分:3)

我认为您需要set_index + unstack

df = df.set_index(['COMMIT_ID','COMMITTER','FILE_NAME'])['CHANGE TYPE']
       .unstack()
      .reset_index()
print (df)
FILE_NAME  COMMIT_ID COMMITTER class.java main.js package.json
0                  1         A       None    None       MODIFY
1                  2         B     DELETE     ADD         None

使用pivot_table的解决方案 - 需要聚合函数,如sum(不带分隔符的连接字符串)或'_'.join(如果重复,则将字符串与分隔符连接起来):

print (df)
   COMMIT_ID     FILE_NAME COMMITTER CHANGE TYPE
0          1  package.json         A      MODIFY
1          2       main.js         B         ADD
2          2    class.java         B      DELETE
3          2    class.java         B         ADD


df = df.pivot_table(index=['COMMIT_ID','COMMITTER'], 
                    columns='FILE_NAME', 
                    values='CHANGE TYPE', 
                    aggfunc='sum').reset_index()
print (df)
FILE_NAME  COMMIT_ID COMMITTER class.java main.js package.json
0                  1         A       None    None       MODIFY
1                  2         B  DELETEADD     ADD         None

或者:

df = df.pivot_table(index=['COMMIT_ID','COMMITTER'], 
                    columns='FILE_NAME', 
                    values='CHANGE TYPE', 
                    aggfunc='_'.join).reset_index()
print (df)
FILE_NAME  COMMIT_ID COMMITTER  class.java main.js package.json
0                  1         A        None    None       MODIFY
1                  2         B  DELETE_ADD     ADD         None

first聚合也有效,但您可以丢失重复值:

df = df.pivot_table(index=['COMMIT_ID','COMMITTER'], 
                    columns='FILE_NAME', 
                    values='CHANGE TYPE', 
                    aggfunc='first').reset_index()
print (df)
FILE_NAME  COMMIT_ID COMMITTER class.java main.js package.json
0                  1         A       None    None       MODIFY
1                  2         B     DELETE     ADD         None

最后一次重命名列名称添加rename_axis

df = df.rename_axis(None, axis=1)
print (df)
   COMMIT_ID COMMITTER class.java main.js package.json
0          1         A       None    None       MODIFY
1          2         B  DELETEADD     ADD         None