Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

python - Numpy array, fill empty values for a single column

I have an array in numpy, which was generated using np.array() from a python list so my entries are strings, but some of the values are blank. Here is an example array:

['1', '1', '1', '1']
['1', '1', '', '1']
['1', '1', '1', '1']
['1', '', '1', '1']

There is no 'NaN' or 'None', it is blank. I want to be able to fill all the blank cells in a particular column with the same value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use numpy.where() to achieve this.

In [8]: arr = numpy.array(['','1','2','3',''])

In [9]: arr[numpy.where(arr=='')] = '0'

In [10]: arr
Out[10]:
array(['0', '1', '2', '3', '0'],
      dtype='|S1')

Edit As @mgilson pointed out, you could just do:

arr[arr==''] = '0'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...