Home > Back-end >  change number negative sign position
change number negative sign position

Time:08-18

Hello I have the following example of df

 col1      col2
 12.4      12.32
 11.4-     2.3
 2.0-      1.1

I need the negative sign to be at the beginning of the number and not at the end

 col1      col2
 12.4      12.32
 -11.4     2.3
 -2.0      1.1

I am trying with the following function, so far I can get the data with the sign and print them correctly but I no longer know how to replace them in my column

updated_data = '' # iterate over the content
for line in df["col1"]:
# removing last word
    updated_line = ' '.join(str(line).split('-')[:-1])
    print(updated_line)

Could you help me please? or if there is an easier way to do it I would appreciate it

CodePudding user response:

here is one way to do it, using np.where

#check if string contains - at the end, and then converting it float after removing '-' and multiplying by -1


df['col1']=np.where(df['col1'].str.strip().str.endswith('-'),
         df['col1'].str.replace(r'-','',regex=True).astype('float')*(-1),
         df['col1']
        )
df
     col1    col2
0    12.4   12.32
1   -11.4    2.30
2    -2.0    1.10
  • Related