用“符号"填充数据框.数字 [英] Filling a DataFrame with "sign" numbers

查看:74
本文介绍了用“符号"填充数据框.数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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?

提前谢谢

推荐答案

您可以使用 boolean indexing :

You can use 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

这篇关于用“符号"填充数据框.数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆