Removing commas and unlisting a dataframe

随声附和 提交于 2019-12-11 15:08:22

问题


Background

I have the following sample 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']

                 })

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

Desired 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

Question

How do I get my desired output which is 1) unlisted and 2) has the commas removed?

I tried Removing lists from each cell in pandas dataframe to no avail


回答1:


As you confirmed, the solution is simple. For one column:

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

For all columns having lists, you need using apply and assign back as follows:

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


来源:https://stackoverflow.com/questions/56910537/removing-commas-and-unlisting-a-dataframe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!