Issue
I have a pandas dataframe like below
id name value1 value2 value3 Type
=======================================================
1 AAA 1.0 1.5 1.8 NEW
2 BBB 2.0 2.3 2.5 NEW
3 CCC 3.0 3.6 3.7 NEW
I have convert the above df into something like below so that i can join it to another df based on name (which will be unique in my case)
Type AAA BBB CCC
================================================================
NEW [1.0, 1.5, 1.8] [2.0, 2.3, 2.5] [3.0, 3.6, 3.7]
Is there any way to achieve this instead of having too many looping statements.
Any help is much appreciated.
Thanks,
Solution
A possible solution, which first adds column value
containing the list and then uses pivot
:
(df.assign(value=df.loc[:, 'value1':'value3'].apply(list, axis=1))
.pivot(index='Type', columns='name', values='value')
.rename_axis(None, axis=1).reset_index())
Output:
Type AAA BBB CCC
0 NEW [1.0, 1.5, 1.8] [2.0, 2.3, 2.5] [3.0, 3.6, 3.7]
Answered By - PaulS
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.