Python 替换字符串';1年';与';1';在数据集中

Python 替换字符串';1年';与';1';在数据集中,python,Python,我有一个数据集,需要用另一组字符串值替换一些字符串值。在本例中,我想将字符串“1年”替换为“1”。我已经使用了代码- loan_data['emp_length_int']=loan_data['emp_length'].str.replace("1 year","1") 然后使用unique功能检查值是否已更改但无效- array(['10+ ', '0', '1 year', '3 ', '8 ', '9 ', '4 ', '5 ', '6 ','2 ', '7 ', na

我有一个数据集,需要用另一组字符串值替换一些字符串值。在本例中,我想将字符串“1年”替换为“1”。我已经使用了代码-

loan_data['emp_length_int']=loan_data['emp_length'].str.replace("1 year","1")
然后使用unique功能检查值是否已更改但无效-

array(['10+  ', '0', '1 year', '3  ', '8  ', '9  ', '4  ', '5  ', '6  ','2 ', '7  ', nan], dtype=object)

我哪里出错了?

不清楚您使用的数据集/数组是什么类型。假设它是一个np数组;这个loan_data['emp_length_int']返回数组

array(['10+ ', '0', '1 year', '3 ', '8 ', '9 ', '4 ', '5 ', '6 ', '2 ', '7 ', nan], dtype=object)

for i in range(len(loan_data['emp_length_int'])):
    loan_data['emp_length_int'][i] = loan_data['emp_length_int'][i].replace('1 year','1')
我们应该做到这一点

如果且仅当贷款数据['emp_length']='1年',您所做的将仅用“1”替换“1年”

它在数组上不起作用,因为数组是数组。不是一串。str.replace()仅对字符串执行此操作。请检查数组类型上的文档以及replace()函数


不清楚您使用的数据集/数组的tpye是什么。假设它是一个np数组;这个loan_data['emp_length_int']返回数组

array(['10+ ', '0', '1 year', '3 ', '8 ', '9 ', '4 ', '5 ', '6 ', '2 ', '7 ', nan], dtype=object)

for i in range(len(loan_data['emp_length_int'])):
    loan_data['emp_length_int'][i] = loan_data['emp_length_int'][i].replace('1 year','1')
我们应该做到这一点

如果且仅当贷款数据['emp_length']='1年',您所做的将仅用“1”替换“1年”

它在数组上不起作用,因为数组是数组。不是一串。str.replace()仅对字符串执行此操作。请检查数组类型上的文档以及replace()函数


.str.
做什么?它不会导致错误吗?
string.replace(“1年”、“1”)
是您需要如何使用的,不确定您如何能够使用
某物。str.replace(“1年”、“1”)
它必须抛出错误
.str.
做什么?它不会导致错误吗?
string.replace(“1年”、“1”)
是您需要如何使用的,但不确定您如何能够使用
something.str.replace(“1年”、“1”)
它必须抛出错误