Python Pandas 用相反的符号替换值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29299597/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:07:01  来源:igfitidea点击:

Python Pandas replace values by their opposite sign

pythonpandasdata-processing

提问by eleijonmarck

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

请帮助我朝着正确的方向前进

回答by EdChum

Just call abs:

只需致电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 NaNrows, call locon the index and assign the negative values:

另一种方法是创建一个布尔掩码,删除NaN行,调用loc索引并分配负值:

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

回答by Akash Nayak

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.

我认为这会帮助你解决这个问题。