Skip to main content
 首页 » 编程设计

python之将列表中元组形式的单行字符串拆分为多行(等于元组数)

2025年04月02日28shanyou

我有一个 DataFrame,其中一行包含字符串元组及其 ID。

喜欢:

id         words 
223        [('flying bird','round place'),('blue sky','red rose')] 
368        [('fairy tales','great day'),('show time','break free'),('noise free')] 

我要:

id         words 
223        [('flying bird','round place')] 
223        [('blue sky','red rose')] 
368        ['fairy tales','great day')] 
368        [('show time','break free')] 
368        [('noise free')]] 

在 python pandas 数据框中。

请您参考如下方法:

另一种解决方案 set_index和 stack .最后一列words被转换为元组的list,但如果元组只有一个元素,则需要添加,:

df.set_index('id', inplace=True) 
df = df.words.apply(pd.Series) 
df = df.stack().reset_index(drop=True, level=1).reset_index(name='words') 
 
df['words'] = df.words.apply(lambda x: [(x,)] if len(x) > 2 else [x] ) 
print (df) 
    id                         words 
0  223  [(flying bird, round place)] 
1  223        [(blue sky, red rose)] 
2  368    [(fairy tales, great day)] 
3  368     [(show time, break free)] 
4  368               [(noise free,)]