Python Pandas replace values by their opposite sign

一笑奈何 提交于 2019-12-05 16:24:53

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!