How to use pandas.DataFrame columns as index, columns and values?

I cannot figure out how to ask this question in a searchable way, but I feel that this is a simple question.

Given a pandas Dataframe object, I would like to use one column as an index, one column as columns and a third column as values.

For instance:

abc 0 1 dog 2 1 1 cat 1 2 1 rat 6 3 2 cat 2 4 3 dog 1 5 3 cat 4 

I would like the custom column β€œa” to be both my index values, column β€œb” as my columns, and column β€œc” as values ​​for each row / column, and fill 0 for missing values ​​(if possible) . For instance...

  dog cat rat 1 2 1 6 2 0 2 0 3 1 4 0 

This would be the matrix 'a' by 'b' with 'c' as fill values

+5
source share
2 answers

This is (almost) exactly the same as you express it:

 df.pivot_table(index="a", columns="b", values="c", fill_value=0) 

gives

 b cat dog rat a 1 1 2 6 2 2 0 0 3 4 1 0 

NTN

+3
source

http://pandas.pydata.org/pandas-docs/dev/reshaping.html

Starting with the sample data you give

 df.pivot(index='a', columns='b', values='c') 

will produce almost exactly what you want.

FWIW, df.melt () is the opposite conversion.

+1
source

Source: https://habr.com/ru/post/1214102/


All Articles