Keys and values in separate columns, I want to create columns with corresponding values

51 Views Asked by At

Sorry for the confusing title! I have the following columns in my dataframe:

Column A                         Column B
['Dogs','Cats','Horses']       [0.5,0.25,0.25]    
['Dogs']                       [1.0]   
['Cats','Horses']             [0.75,0.25]   

And the output I would like is:

Dogs                        Cats                        Horses
0.5                         0.25                        0.25   
1.0                         0                           0  
0                           0.75                        0.25

Thank you in advance! :)

I tried the following code:

keys = set([key for row in df['column_a'] for key in row])

for key in keys:
    df[key] = 0.0

for i, row in df.iterrows():
    for key, value in zip(row['column_a'], row['column_b']):
        if isinstance(value, list):
            for demography, score in zip(key, value):
                df.at[i, demography] = score
        else:
            df.at[i, key] = value

df.drop(columns=['column_a', 'column_b'], inplace=True)

and got an error "TypeError: 'float' object is not iterable"

1

There are 1 best solutions below

6
Georgina Skibinski On

It's simple pandas oneliner:

>>> df.explode(list(df.columns)).pivot(columns="Column A", values="Column B").fillna(0)
Column A  Cats  Dogs  Horses
0         0.25   0.5    0.25
1         0.00   1.0    0.00
2         0.75   0.0    0.25

explode will explode in parallel all columns, then pivot will reshape the result.