Python为何出现AttributeError: numpy.ndarray无replace属性?如何解决?
The Problem
You pulled unique city names from a CSV using pandas, which returned a NumPy array. When you tried using replace() to swap spaces with underscores, you ran into an AttributeError—that's because NumPy arrays don't have a built-in replace method for handling string elements directly.
The Solutions
Here are three simple, reliable ways to fix this:
Use NumPy's
vectorizeto apply string replace
This tool lets you apply Python's stringreplacemethod across every element in the array:import numpy as np my_cities = np.vectorize(lambda city: city.replace(" ", "_"))(my_city)Leverage pandas Series string methods
Since you started with pandas, converting the array back to a Series makes it easy to use pandas' dedicated string handling tools:import pandas as pd my_cities = pd.Series(my_city).str.replace(" ", "_").to_numpy()List comprehension + convert back to NumPy array
A straightforward Python list comprehension works too—process each city name individually, then convert the result back to a NumPy array:my_cities = np.array([city.replace(" ", "_") for city in my_city])
Why the Original Code Failed
Your my_city variable is a numpy.ndarray, not a Python list or pandas Series. The replace() method belongs to individual Python string objects, not the NumPy array itself. All the solutions above work by applying the string replace() method to each element in the array, either via vectorization, pandas' utilities, or explicit iteration.
内容的提问来源于stack exchange,提问作者NewInPython

