HappyPy
HappyPy

Reputation: 10697

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

Upvotes: 0

Views: 107

Answers (1)

MaxU - stand with Ukraine
MaxU - stand with Ukraine

Reputation: 210842

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

Upvotes: 1

Related Questions