pandas 用“符号”数字填充数据帧

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37377478/
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-14 01:16:13  来源:igfitidea点击:

Filling a DataFrame with "sign" numbers

pythonpandas

提问by vsoler

I have a DataFrame full of floats (positive and negative) and some NaN. I'd like to replace every single float number with its sign:

我有一个充满浮点数(正数和负数)和一些 NaN 的 DataFrame。我想用它的符号替换每个浮点数:

if it's NaN -> it remains Nan
if positive -> replace with 1
if negative -> replace with -1
if zero -> leave it as 0

Any suggestions to make this massive replacement?

有什么建议可以进行这种大规模的更换吗?

Thank you in advance

先感谢您

采纳答案by jezrael

You can use boolean indexing:

您可以使用boolean indexing

import pandas as pd
import numpy as np

df = pd.DataFrame({'A':[-1,3,0,5],
                   'B':[4,5,6,5],
                   'C':[8,-9,np.nan,7]})

print (df)
   A  B    C
0 -1  4  8.0
1  3  5 -9.0
2  0  6  NaN
3  5  5  7.0
print (df > 0)
       A     B      C
0  False  True   True
1   True  True  False
2  False  True  False
3   True  True   True

print (df < 0)
       A      B      C
0   True  False  False
1  False  False   True
2  False  False  False
3  False  False  False

df[df > 0] = 1
df[df < 0] = -1

print (df)
   A  B    C
0 -1  1  1.0
1  1  1 -1.0
2  0  1  NaN
3  1  1  1.0

回答by ayhan

You can use np.sign:

您可以使用np.sign

df
Out[100]: 
     A
0 -4.0
1  2.0
2  NaN
3  0.0

import numpy as np
np.sign(df["A"])

Out[101]: 
0   -1.0
1    1.0
2    NaN
3    0.0
Name: A, dtype: float64

In order to apply to all columns, you can directly pass the dataframe:

为了适用于所有列,您可以直接传递数据框:

df
Out[121]: 
          0         1         2         3
0 -2.932447 -1.686652       NaN -0.908441
1  1.254436  0.000000  0.072242  0.796944
2  2.626737  0.169639 -1.457195  1.169238
3  0.000000 -1.174251  0.660111  1.115518
4 -1.998091 -0.125095  0.000000 -0.506782

np.sign(df)
Out[122]: 
     0    1    2    3
0 -1.0 -1.0  NaN -1.0
1  1.0  0.0  1.0  1.0
2  1.0  1.0 -1.0  1.0
3  0.0 -1.0  1.0  1.0
4 -1.0 -1.0  0.0 -1.0

回答by Vedang Mehta

Code -

代码 -

import pandas as pd


df = pd.DataFrame({'x' : [-5.3, 2.5, 0, float('nan')]})

df['x'] = df['x'].apply(func = lambda x : x if not x else x // abs(x))

print(df)

Output -

输出 -

    x
0  -1
1   1
2   0
3 NaN