Sorry for the confusing title, I'm not sure what's the best way to describe the problem. But an example should be helpful.
Assume this is my pandas
dataframe
col1 = ['A', 'A', 'B', 'B', 'C', 'C', 'D', 'D', 'E', 'E']
col2 = ['a', 'c', 'd', 'e', 'b', 'c', 'd', 'e', 'a', 'c']
col3 = [143, 62, 12, 75, 9, 71, 40, 95, 23, 13]
df = pd.DataFrame([col1,col2,col3]).transpose()
df.columns = ['col1', 'col2', 'col3']
df
col1 col2 col3
0 A a 143
1 A c 62
2 B d 12
3 B e 75
4 C b 9
5 C c 71
6 D d 40
7 D e 95
8 E a 23
9 E c 13
and I would like to use unique values in col1
as my new df's row names, and unique values from col2
as columns names, then fill col3
values in the new df and fill in the blank with 0. For example, newdf.loc['A','a']
will return 143
, and newdf.loc['C','a']
will be 0
. The newdf
should be a 5x5
dataframe.
The easiest way is to do a double for
loop, but I'm curious if there's an easier way to do it.
I hope my explanation makes sense, and thank you guys for helping!