删除逗号并取消列出数据框 [英] Removing commas and unlisting a dataframe

查看:63
本文介绍了删除逗号并取消列出数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

背景

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

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

我尝试了从熊猫数据框中的每个单元格中删除列表无济于事

推荐答案

您已经确认,解决方案很简单.对于一列:

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

对于所有具有列表的列,您需要使用apply并按以下方式分配回去:

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

这篇关于删除逗号并取消列出数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆