Below you can see the format of my data. I am trying to pivot this data into a desirable format. Below you can see my data
df = pd.DataFrame({"id_n":["1","2","3","4","5","6","7","8","9","10","11","12","13","14","15","16","17","18","19"],
"kind_i":["1", "2", "3","4","5","6","7","8","9","10","11","12","13","14","19","20","23","25","26"],
"gross_i":[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19]})
table = pd.pivot_table(df, values=['gross_i'], index=['id_n'],
columns=['kind_i'], aggfunc=np.sum, fill_value=0)
After pivoting above you can see the appearance of my table.
I am not satisfied with the titles of columns and I want to change in format e.g kind_1, kind_2, kind_3 ... and kind_26. Please see pic below.
So can anybody help me how to do this ?
CodePudding user response:
Change from dataframe pivot to series pivot
, then add_prefix
table = pd.pivot_table(df, values='gross_i', index='id_n',
columns='kind_i', aggfunc=np.sum, fill_value=0).add_prefix('kind_')
table
Out[462]:
kind_i kind_1 kind_10 kind_11 kind_12 ... kind_6 kind_7 kind_8 kind_9
id_n ...
1 1 0 0 0 ... 0 0 0 0