python suppress minus charactere

44 Views Asked by At

On Python3, I have ome data on array:

tst_val:  ['', '1', '--2147483648-0', '', 0]    => bad values
tst_val:  ['1', '0', '0']                       => values OK
tst_val:  ['0', '0', '1']                       => values OK
tst_val:  ['1', '-0', '-1']                     => bad values

Then tabVal_sub = str(tst_val).split(' ')

In my sub_val, I only want values, properly formatted, like 0 or 1 (int format preferred). If value is not '1' or '0', replace by default with '0'.

I tried to make a:

for k in range(1, 4):
#    print ('Check tabVal_sub ' + str(k))
    l = [0, 1]
    if int(tabVal_sub[k]) not in l:
        tabVal_sub[k] = 0

But, it's crashing ! (go out of try catch)

Please, do you have an idea to fix it?

Thx ;o)

2

There are 2 best solutions below

2
AKX On BEST ANSWER

If your problem truly is

In my sub_val, I only want values, properly formatted, like 0 or 1 (int format preferred). If value is not '1' or '0', replace by default with '0'.

then the solution is simply

sub_val = [(int(val) if val in ("1", "0") else 0) for val in tst_val]
0
irum On

I succeeded with this:

# Clean up Dataframe to avoid data   like "| 0 --2147483648-0 |"
# into |V1-V2 -Vy | (if after '--' we have more than 2 digits)
# and suppress all '--' and '-'

df = df.replace(r'--\d{2,}', ' 0 ', regex=True).\
    replace(r'--', '', regex=True).replace(r'-', '', regex=True)