简体   繁体   中英

Extract non- empty values from the regex array output in python

I have a column of type numpy.ndarray which looks like:

         col
    ['','','5','']
    ['','8']
    ['6','','']
    ['7']
    []
    ['5']

I want the ouput like this :

         col
          5
          8
          6
          7
          0
          5

How can I do this in python.Any help is highly appreciated.

To convert the data to numeric values you could use:

import numpy as np
import pandas as pd
data = list(map(np.array, [ ['','','5',''], ['','8'], ['6','',''], ['7'], [], ['5']]))
df = pd.DataFrame({'col': data})
df['col'] = pd.to_numeric(df['col'].str.join('')).fillna(0).astype(int)
print(df)

yields

   col
0    5
1    8
2    6
3    7
4    0
5    5

To convert the data to strings use:

df['col'] = df['col'].str.join('').replace('', '0')

The result looks the same, but the dtype of the column is object since the values are strings.


If there is more than one number in some rows and you wish to pick the largest, then you'll have to loop through each item in each row, convert each string to a numeric value and take the max:

import numpy as np
import pandas as pd
data = list(map(np.array, [ ['','','5','6'], ['','8'], ['6','',''], ['7'], [], ['5']]))
df = pd.DataFrame({'col': data})
df['col'] = [max([int(xi) if xi else 0 for xi in x] or [0]) for x in df['col']]
print(df)

yields

   col
0    6   # <-- note  ['','','5','6'] was converted to 6
1    8
2    6
3    7
4    0
5    5

For versions of pandas prior to 0.17, you could use df.convert_objects instead:

import numpy as np
import pandas as pd
data = list(map(np.array, [ ['','','5',''], ['','8'], ['6','',''], ['7'], [], ['5']]))
df = pd.DataFrame({'col': data})
df['col'] = df['col'].str.join('').replace('', '0')
df = df.convert_objects(convert_numeric=True)

I'll leave you with this :

>>> l=['', '5', '', '']
>>> l = [x for x in l if not len(x) == 0]
>>> l
>>> ['5']

You can do the same thing using lambda and filter

>>> l
['', '1', '']
>>> l = filter(lambda x: not len(x)==0, l)
>>> l
['1']

The next step would be iterating through the rows of the array and implementing one of these two ideas.

Someone shows how this is done here: Iterating over Numpy matrix rows to apply a function each?

edit: maybe this is down-voted, but I made it on purpose to not give the final code.

     xn = array([['', '', '5', ''], ['', '8'], ['6', '', ''], ['7'], [], ['5']],
    dtype=object)

        In [20]: for a in x:
   ....:     if len(a)==0:
   ....:         print 0
   ....:     else:
   ....:         for b in a:
   ....:             if b:
   ....:                 print b
   ....:
5
8
6
7
0
5

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM