Reputation: 1323
I have a pandas DataFrame
of the form:
age begin end product_id
0 40 1578178800 1579388400 [3, 4]
1 30 1578178800 1579388400 [3, 4, 6, 2, 5, 1]
2 30 1578178800 1578265200 [6]
3 58 1578178800 1578265200 [6]
4 30 1578178800 1578265200 [6]
Since theproduct_id is the combination of the products the customers choose. For example: 1 - electronics, 2 - automobiles, 3- accessories, 4 - Robots, 5 - Training, 6 - Other
I would like to have the DataFrame
in the form below without the list around it:
age begin end product_id
0 40 1578178800 1579388400 accessories, Robots
1 30 1578178800 1579388400 accessories, Robots, Other, automobiles, Training, electronics
2 30 1578178800 1578265200 Other
3 58 1578178800 1578265200 Other
4 30 1578178800 1578265200 Other
Upvotes: 4
Views: 555
Reputation: 862581
Use list comprehension with map values by dictionary and convert to joined strings:
d = {1:'electronics',
2: 'automobiles',
3:'accessories',
4:'Robots',
5:'Training',
6: 'Other'}
df['product_id'] = df['product_id'].map(lambda x: ', '.join(d[y] for y in x))
print (df)
age begin end \
0 40 1578178800 1579388400
1 30 1578178800 1579388400
2 30 1578178800 1578265200
3 58 1578178800 1578265200
4 30 1578178800 1578265200
product_id
0 accessories, Robots
1 accessories, Robots, Other, automobiles, Train...
2 Other
3 Other
4 Other
Or:
df['product_id'] = [', '.join(d[y] for y in x) for x in df['product_id']]
Upvotes: 2