8

I am trying to "clean" some data. I have values which are negative, which they cannot be. And I would like to replace all values that are negative to their corresponding positive values.

A    | B     | C
-1.9 | -0.2  | 'Hello'
1.2  | 0.3   | 'World'

I would like this to become

A    | B     | C
1.9  | 0.2   | 'Hello'
1.2  | 0.3   | 'World'

As of now I have just begun writing the replace statement

df.replace(df.loc[(df['A'] < 0) & (df['B'] < 0)],df * -1,inplace=True)

Please help me in the right direction

2 Answers 2

14

Just call abs:

In [349]:

df = df.abs()
df
Out[349]:
     A    B
0  1.9  0.2
1  1.2  0.3

Another method would be to create a boolean mask, drop the NaN rows, call loc on the index and assign the negative values:

df.loc[df[df<0].dropna().index] = -df

EDIT

For the situation where you have strings the following would work:

In [399]:

df[df.columns[df.dtypes != np.object]] = df[df.columns[df.dtypes != np.object]].abs()
df
Out[399]:
     A    B      C
0  1.9  0.2  Hello
1  1.2  0.3  World
0
1

You can be use this way:

first make column as a string:

df['A']=df['A'].astype('str')

df['B']=df['B'].astype('str')

Then use replace function:

df['A']=df['A'].str.replace('-','')

df['B']=df['B'].str.replace('-','')

then make it as float data type:

df['A']=df['A'].astype('float')
df['B']=df['B'].astype('float')

I think this will be help you in this problem.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.