1

I would like to transform a table which looks similiar to this below:

X|Y|Z|
1|2|3|
3|5|2|
4|2|1|

The result, I want to achive, should look like that:

col|1|2|3|4|5|
X |1|0|1|0|0|
Y |0|2|0|0|1|
Z |1|1|1|0|0|

So, after transformation the new columns should be unique values from previous table, the new values should be populated with count/appearance, and in the index should be the old column names.

I got stuck and i do not know hot to handle with cause I am a newbe in python, so thanks in advance for support.

Regards,

guddy_7

guddy_7
  • 13
  • 2

1 Answers1

3

Use apply with value_counts, replace missing values to 0 and transpose by T:

df = df.apply(pd.value_counts).fillna(0).astype(int).T
print (df)
   1  2  3  4  5
X  1  0  1  1  0
Y  0  2  0  0  1
Z  1  1  1  0  0
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252