Reputation: 8854
I have a pandas dataframe where the Items columns is a list.
cust_id Items
100 ['item1','item2','item3']
101 ['item5','item8','item9']
102 ['item2','item4']
I want to convert the above dataframe to the below format.
cust_id Items
100 item1 item2 item3
101 item5 item8 item9
102 item2 item4
I tried using the pandas built in string replace function put its returning the original column without actually performing the string replace operation.
df['Items']=(df['Items'].astype(str)).replace({"['":"", "', '":" ", "']":"" },method='string')
Please advise
Update:
I used the below code to create the original dataframe.
df=df1.groupby(['cust_id'])['Items'].apply(list).reset_index()
Upvotes: 2
Views: 173
Reputation: 90979
If the elements are really list
, then you can use str.join()
on the list along with series.apply
method . Example -
In [159]: df = pd.DataFrame([[100,['item1','item2','item3']],[101,['item5','item8','item9']],[102,['item2','item4']]],columns=['cust_id','Items'])
In [160]: df
Out[160]:
cust_id Items
0 100 [item1, item2, item3]
1 101 [item5, item8, item9]
2 102 [item2, item4]
In [161]: df['Items'] = df['Items'].apply(' '.join)
In [162]: df
Out[162]:
cust_id Items
0 100 item1 item2 item3
1 101 item5 item8 item9
2 102 item2 item4
Upvotes: 4