user1823812
user1823812

Reputation: 199

Pandas change dataframe structure

Im currently following Wes McKinneys tutorials on pandas and I was wondering if it is possible to do a certain thing in it. I'll explain this with an example: I have a Data Frame :

    A   B   C
0   1 foo   data1
1   5 foo2  data2
2   8 foo3  data3
3   6 foo   data4
4   5 foo3  data5
5   3 foo2  data1

I want to transform the previous data frame to a new one that looks like this:

      data1 data2 data3 data4 data5
foo    1      0     0     6     0
foo2   3      5     0     0     0
foo3   0      0     8     0     5

Also, I can't have the same foo-data combo twice, so I dont care about overwriting values.

Is this possible with pandas?

Upvotes: 1

Views: 1739

Answers (1)

Fabio Lamanna
Fabio Lamanna

Reputation: 21552

You can pivot your original dataframe df setting the correct values for index, columns and values.

a = df.pivot_table(index='B',columns='C',values='A').fillna(0)

The fillna(0) replace NaN with 0 values.

C     data1  data2  data3  data4  data5
B                                      
foo       1      0      0      6      0
foo2      3      5      0      0      0
foo3      0      0      8      0      5

Upvotes: 5

Related Questions