您如何一次删除所有列中的所有“£”和“,”,而不一次删除?

时间:2019-07-23 00:50:55

标签: python string dataframe lambda

需要使用python从我的jupyter笔记本中的excel文件中删除所有“£”和“,”。我知道如何一次处理1列,但是有很多列,我想一次删除所有的“£”和“,”并重新保存。

从这里开始,我尝试了很多不同的方法,但是它们一次只显示一个列表或一列,我需要一次删除所有的“£”和“”,因为这太浪费时间了。

def up?(site)
  Net::HTTP.new(site).head('/').kind_of? Net::HTTPOK
end

up? 'www.google.com' #=> true

2 个答案:

答案 0 :(得分:1)

这是replace

的一种方法
df=df.replace({'£':'',',':''},regex=True)
df
       total  refunded       tax
0   43622.61   4528.86  16975.51
1  133873.05  37093.26   3561.38
2   19253.19  14253.07   2544.06
3  153947.84  11993.01   2779.59
4  227844.55  29682.94  52195.53

答案 1 :(得分:0)

您可以使用apply方法将函数应用于pandas数据框的所有列。

import pandas as pd
import io

data = io.StringIO("""
total refunded tax
£43,622.61 £4,528.86 £16,975.51
£133,873.05 £37,093.26 £3,561.38
£19,253.19 £14,253.07 £2,544.06
£153,947.84 £11,993.01 £2,779.59
£227,844.55 £29,682.94 £52,195.53
""")

df = pd.read_csv(data, sep=' ')

def cleaner(x):
    cleaned = [''.join([c for c in s if c not in {'£', ','}]) for s in x]
    return cleaned

df = df.apply(cleaner)

print(df.to_string())

#        total  refunded       tax
# 0   43622.61   4528.86  16975.51
# 1  133873.05  37093.26   3561.38
# 2   19253.19  14253.07   2544.06
# 3  153947.84  11993.01   2779.59
# 4  227844.55  29682.94  52195.53