Converting empty strings to 0 using Numpy

前端 未结 3 1296
生来不讨喜
生来不讨喜 2020-12-11 07:06

I have a numpy array where each element looks something like this:

[\'3\' \'1\' \'35\' \'0\' \'0\' \'8.05\' \'2\']
[\'3\' \'1\' \'\' \'0\' \'0\' \'8.4583\' \         


        
相关标签:
3条回答
  • 2020-12-11 07:46

    Here is an approach that uses map:

    def FloatOrZero(value):
        try:
            return float(value)
        except:
            return 0.0
    
    
    print map(FloatOrZero, ['3', '1', '', '0', '0', '8.4583', '0'])
    

    Outputs:

    [3.0, 1.0, 0.0, 0.0, 0.0, 8.4583, 0.0]
    

    In case you needed more flexibility

    0 讨论(0)
  • 2020-12-11 07:58

    Just do this first:

    s = np.array(['1', '0', ''])
    s[s==''] = '0'
    
    s.astype(float)
    #array([ 1.,  0.,  0.])
    
    0 讨论(0)
  • 2020-12-11 08:09

    If your array is t:

    t[t=='']='0'
    

    and then convert it.

    Explanation:

    t=='' creates a boolean array with the same shape as t that has a True value where the corresponding t value is an empty space. This boolean array is then used to assign '0' only to the appropriate indices in the original t.

    0 讨论(0)
提交回复
热议问题