删除逗号并取消列出数据框

时间:2019-07-06 01:11:23

标签: python-3.x pandas list dataframe nlp

背景

我有以下示例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)已删除逗号?

我尝试Removing lists from each cell in pandas dataframe无济于事

1 个答案:

答案 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