[英]Why do I get AttributeError: 'numpy.ndarray' object has no attribute 'replace' in python?
I am trying to standardize my data in my csv file:我正在尝试在我的 csv 文件中标准化我的数据:
import pandas as pd
my_city = pd.read_csv('sample4_addlink.csv')['City'].unique()
my_city
Out[70]:
array(['Lancaster', 'Canton', 'Edison', ..., 'Upton', 'Irvington',
'El Cerrito'], dtype=object)
Now as you see in my_city, there are some cities with space between names like El Cerrito.现在,正如您在 my_city 中看到的那样,有些城市的名称之间有空格,例如 El Cerrito。 I want to replace the space with an underscore
我想用下划线替换空格
my_cities =my_city.replace(" ", "_")
Traceback (most recent call last):
File "<ipython-input-71-53c4a0662dd7>", line 1, in <module>
my_cities =my_city.replace(" ", "_")
AttributeError: 'numpy.ndarray' object has no attribute 'replace'
I get this error when I use the .replace function.使用 .replace 函数时出现此错误。 What is the best way to get around this?
解决这个问题的最佳方法是什么?
It's because unique
returns an ndarray
or ExtensionArray
object depending on the data type of the input series.这是因为
unique
根据输入系列的数据类型返回ndarray
或ExtensionArray
对象。
Use drop_duplicates
and the str
accessor instead:改用
drop_duplicates
和str
访问器:
my_city = pd.read_csv('sample4_addlink.csv')['City'].drop_duplicates().str.replace(' ', '_')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.