简体   繁体   中英

Replace commas with new lines for string in column of Pandas DataFrame

I have some DataFrame:

d = {'fruit': ['apple', 'pear', 'peach'], 'values': ['apple_1_0,peach_1_5','pear_1_3','mango_1_0,banana_1_0,pineapple_1_10']}
df = pd.DataFrame(data=d)
df

fruit   values
0   apple   apple_1_0,peach_1_5
1   pear    pear_1_3
2   peach   mango_1_0,banana_1_0,pineapple_1_10

I'd like to separate the strings in the values column by new lines instead of by commas, eg:

    fruit   values
    0   apple   apple_1_0
                peach_1_5
    1   pear    pear_1_3
    2   peach   mango_1_0
                banana_1_0
                pineapple_1_10

Put the values into list using .str.split and explode()

df=df.assign(values =df['values'].str.split(',')).explode('values')

as noted by @cs95 If you wanted index without repeated values. Please try

df.set_index('fruit', append=True)['values'].str.split(',').explode().to_frame()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM