简体   繁体   中英

replace column in data frame with elements from another column - python

df = pd.DataFrame({'c1':['g1','g1','g1','g2','g2','g2'], 'c2':['x','y','z','x','y','z'], 'v':[72,44,13,53,97,32]})

Is there a way to transform df in a way that v is replaced by the values g1 and g2 from column c1 ?

This is the output I'm trying to achieve:

    c2   g1   g2
0   x    72   53
1   y    44   97
2   z    13   32

use pivot_table() for that:

In [58]: df.pivot_table(index='c2', columns='c1', values='v').reset_index()
Out[58]:
c1 c2  g1  g2
0   x  72  53
1   y  44  97
2   z  13  32

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