背景
我有以下玩具df
包含列中的列表Before
and After
如下所示
import pandas as pd
before = [list(['in', 'the', 'bright', 'blue', 'box']),
list(['because','they','go','really','fast']),
list(['to','ride','and','have','fun'])]
after = [list(['there', 'are', 'many', 'different']),
list(['i','like','a','lot','of', 'sports']),
list(['the','middle','east','has','many'])]
df= pd.DataFrame({'Before' : before,
'After' : after,
'P_ID': [1,2,3],
'Word' : ['crayons', 'cars', 'camels'],
'N_ID' : ['A1', 'A2', 'A3']
})
Output
After Before N_ID P_ID Word
0 [in, the, bright, blue, box] [there, are, many, different] A1 1 crayons
1 [because, they, go, really, fast] [i, like, a, lot, of, sports ] A2 2 cars
2 [to, ride, and, have, fun] [the, middle, east, has, many] A3 3 camels
Problem
使用以下代码块:
df.loc[:, ['After', 'Before']] = df[['After', 'Before']].apply(lambda x: x.str[0].str.replace(',', ''))
取自删除逗号并取消列出数据框 https://stackoverflow.com/questions/56910537/removing-commas-and-unlisting-a-dataframe产生以下输出:
接近我想要但不完全想要的输出
After Before N_ID P_ID Word
0 in there A1 1 crayons
1 because i A2 2 cars
2 to the A3 3 camels
这个输出很接近,但不完全是我想要的,因为After
and Before
列只有一个字输出(例如there
)当我想要的输出看起来像这样:
所需输出
After Before N_ID P_ID Word
0 in the bright blue box there are many different A1 1 crayons
1 because they go really fast i like a lot of sports A2 2 cars
2 to ride and have fun the middle east has many A3 3 camels
Question
我怎样才能得到我的所需输出?