为何numpy空数组中存在' '符号?如何创建无该符号的数组?
Great question—let’s break this down clearly, like we’re troubleshooting together.
Why the newline (\n) shows up
First, you’re probably using np.empty() with a string or object dtype, and misunderstanding what np.empty() actually does.
np.empty() doesn’t create an array filled with "empty" values—it only reserves memory space for the array, without initializing the elements. The newline (or any random character you see) is just leftover garbage data from whatever was stored in that memory spot before. If the memory had a \n from a prior operation, that’s what ends up in your array.
Here’s a quick example of this behavior:
import numpy as np # This will pull residual data from memory garbage_arr = np.empty((2,), dtype=str) print(garbage_arr) # Might output something like ['\n' 'test']
How to create a NumPy array without unwanted characters
It depends on what you mean by an "empty" array—here are the two common scenarios:
1. An array filled with empty strings (length > 0)
If you want every element to be a clean empty string ('') instead of garbage, skip np.empty() and use these methods:
- Use
np.full()to explicitly fill the array with empty strings:clean_empty_str_arr = np.full((3,), '', dtype=str) print(clean_empty_str_arr) # Output: ['', '', ''] - Use
np.zeros()(works for string dtypes, since zeros map to empty strings):clean_empty_str_arr = np.zeros((3,), dtype=str) - Directly construct the array with empty string elements:
clean_empty_str_arr = np.array(['', '', ''], dtype=str)
2. A truly empty array (length = 0, no elements)
If you want an array with zero elements (so there’s no space for any unwanted characters at all), create it directly:
truly_empty_arr = np.array([], dtype=str) print(truly_empty_arr) # Output: []
This way, you avoid residual garbage entirely by explicitly initializing the array to your desired state, instead of relying on uninitialized memory.
内容的提问来源于stack exchange,提问作者Tom Jones

