Issue
I've got this DataFrame in Python using pandas:
Column 1 | Column 2 | Column 3 |
---|---|---|
hello | a,b,c | 1,2,3 |
hi | b,c,a | 4,5,6 |
The values in column 3 belong to the categories in column 2. Is there a way to combine columns 2 and 3 that I get this output?
Column 1 | a | b | c |
---|---|---|---|
hello | 1 | 2 | 3 |
hi | 6 | 4 | 5 |
Any advise will be very helpful! Thank you!
Solution
df.apply(lambda x: pd.Series(x['Column 3'].split(','), index=x['Column2'].split(',')), axis=1)
output:
a b c
0 1 2 3
1 4 5 6
result make to df1
and concat
df1 = df.apply(lambda x: pd.Series(x['Column 3'].split(','), index=x['Column2'].split(',')), axis=1)
pd.concat([df['Column 1'], df1], axis=1)
output:
col1 a b c
0 hello 1 2 3
1 hi 4 5 6
Answered By - Panda Kim
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.