首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >删除逗号并取消数据格式

删除逗号并取消数据格式
EN

Stack Overflow用户
提问于 2019-07-06 01:11:23
回答 1查看 148关注 0票数 0

背景

我有下面的示例df

代码语言:javascript
复制
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']

                 })

输出

代码语言:javascript
复制
      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

期望输出

代码语言:javascript
复制
      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,但没有用。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2019-07-06 01:51:11

正如你所证实的,解决办法很简单。一栏:

代码语言:javascript
复制
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并按如下方式重新分配:

代码语言:javascript
复制
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
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/56910537

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档