简体   繁体   中英

Pandas: Converting Columns to Rows based on ID

I am new to pandas,

I have the following dataframe:

df = pd.DataFrame([[1, 'name', 'peter'], [1, 'age', 23], [1, 'height', '185cm']], columns=['id', 'column','value'])

    id  column  value
0   1   name    peter
1   1   age     23
2   1   height  185cm

I need to create a single row for each ID. Like so:

   id  name   age  height
0  1   peter  23   185cm

Any help is greatly appreciated, thank you.

You can use pivot_table with aggregate join :

df = pd.DataFrame([[1, 'name', 'peter'], 
                   [1, 'age', 23], 
                   [1, 'height', '185cm'],
                   [1, 'age', 25]], columns=['id', 'column','value'])
print (df)
   id  column  value
0   1    name  peter
1   1     age     23
2   1  height  185cm
3   1     age     25

df1 = df.astype(str).pivot_table(index="id",columns="column",values="value",aggfunc=','.join)
print (df1)
    column    age height   name
id                         
1       23,25  185cm  peter

Another solution with groupby + apply join and unstack :

df1 = df.astype(str).groupby(["id","column"])["value"].apply(','.join).unstack(fill_value=0)
print (df1)
column    age height   name
id                         
1       23,25  185cm  peter

Assuming your dataframe as "df", below line would help:

df.pivot(index="subject",columns="predicate",values="object")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM