背景
我有以下示例df
:
import pandas as pd
df = pd.DataFrame({'Before' : [['there, are, many, different'],
['i, like, a, lot, of, sports '],
['the, middle, east, has, many']],
'After' : [['in, the, bright, blue, box'],
['because, they, go, really, fast'],
['to, ride, and, have, fun'] ],
'P_ID': [1,2,3],
'Word' : ['crayons', 'cars', 'camels'],
'N_ID' : ['A1', 'A2', 'A3']
})
输出
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
所需的输出
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
问题
我如何获得期望的输出,即 1)未列出且 2)已删除逗号?
答案 0 :(得分:1)
您已确认,解决方案很简单。对于一列:
df.After.str[0].str.replace(',', '')
Out[2821]:
0 in the bright blue box
1 because they go really fast
2 to ride and have fun
Name: After, dtype: object
对于所有具有列表的列,您需要使用apply
并按如下所示进行分配:
df.loc[:, ['After', 'Before']] = df[['After', 'Before']].apply(lambda x: x.str[0].str.replace(',', ''))
Out[2824]:
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