Issue
I need to make a wide-to-long transformation using Pandas.
I tried to make a list (from 1 to the value of the second column) but I got the error below :
Code :
import pandas as pd
df = pd.DataFrame({'Id': ['AA', 'BB', 'CC'], 'Value': [4, 2, 3]})
df['Value'] = df.apply(list(range(1, df['Value'])))
df.explode('Value')
Error :
TypeError: 'Series' object cannot be interpreted as an integer
Do you know you have to fix that or any other suggestions to make this transformation work ?
Solution
You can turn Value
column into list then explode
out = (df.assign(Value=df['Value'].apply(lambda x: range(1, x+1)))
.explode('Value', ignore_index=True))
print(out)
Id Value
0 AA 1
1 AA 2
2 AA 3
3 AA 4
4 BB 1
5 BB 2
6 CC 1
7 CC 2
8 CC 3
Answered By - Ynjxsjmh
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.