python报错—为什么用apply方法使用.replace()方法报错TypeError: str.replace() takes no keyword arguments

项目场景:

1.要求: 将2021金额与2022金额的 ¥ 与 , 这两个符号替换为空。

导入数据及查看数据情况

import os
import pandas as pd 
import numpy as np
#读取文件
def read_file(filepath):
    os.chdir(os.path.dirname(filepath))
    return pd.read_csv(os.path.basename(filepath),encoding='utf-8')
file_pos="F:\\python_test\\data_1.csv"
data_pos=read_file(file_pos)
data_pos

问题描述:

2.1.实现过程一: 使用.replace()方法。

def convert_currency(value):
	'''
	转换字符串数字为float类型
	移除不是数字字符 ¥,
	转换为float类型
	'''
	new_value=value.replace({',':'','¥':''},regex=True)
	print(new_value)
	return new_value.astype('float')

实例调用函数,成功:

#2021金额、2022金额列完整的转换代码
data_pos['2021金额']=convert_currency(data_pos['2021金额'])

用apply调用函数,报错:

data_pos['2021金额'].apply(convert_currency)

在这里插入图片描述
3.1发现问题: 使用实例调用函数成功,使用apply调用函数报错。

2.2.实现过程二: 使用.str.replace()方法。

def convert_currency(value):
	'''
	转换字符串数字为float类型
	移除不是数字字符 ¥,
	转换为float类型
	'''
	new_value=value.str.replace('¥', '').str.replace(',', '')
	return new_value

实例调用函数,成功:

data_pos['2021金额']=convert_currency(data_pos['2021金额'])

用apply调用函数,报错:

data_pos['2021金额'].apply(convert_currency)

在这里插入图片描述

3.2发现问题: 使用实例调用函数成功,使用apply调用函数报错。


原因分析:

  • Series使用apply方法后,apply会自动遍历整个Series,将Series分解为一个个元素(元素数据类型跟数据列的数据类型一致)传入函数中。
    • 对于使用.replace()方法来进行正则替换,会默认为str.replace(old,new,count),并不存在regex这个参数,因此会报错:TypeError: str.replace() takes no keyword arguments

    • 对于使用.str.replace()方法来进行正则替换,.str.replace()只适用于Series对象,不用作用于<class ‘str’>类型,因此会报错AttributeError: ‘str’ object has no attribute ‘str’

对比使用apply调用函数与实例调用函数两种方法,分别传入的数据类型。

def data_type(value):
    '''
    用apply调用函数传入的数据类型
    '''
    print(value)
    print(type(value))
    print('______')
    return value

1、用apply调用函数,传入数据类型

data_pos['2021金额'].apply(data_type)

在这里插入图片描述

2、实例调用函数,传入数据类型

data_type(data_pos['2021金额'])

在这里插入图片描述
从上面可以看出,实例调用函数传入的数据类型是<class ‘pandas.core.series.Series’>,apply方法调用函数传入的数据类型是<class ‘str’>,所以前者使用.replace()与.str.replace()方法都没有报错,后者就会出现前面两种报错提示。详细的.replace()与.str.replace()方法使用可以查看python替换—Series.replace()与Series.str.replace()的区别及为何replace()无效的解决方法


解决方案:实例调用函数。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值