Python – Pandas数据框中使用最新前面的正值替换负值

Python – Pandas数据框中使用最新前面的正值替换负值

我们要用最新前面的正值替换负值。如果没有正值,则该值应更新为0。

输入

例如,输入为−

DataFrame:  
One  two
0  -2   -3
1   4   -7
2   6    5
3   0   -9

输出

输出应为−

   One two
0   0   0
1   7   0
2   4   2
3   0   2

数据框遮掩用于替换负值。为了填补缺失值,我们使用向前填充。首先,让我们创建pandas dataframe−

# 创建pandas dataframe
df = pd.DataFrame({'One': [-3, 7, 4, 0], 'two': [-6, -1, 2, -8]})

让我们执行遮罩−

df = df.mask(df.lt(0)).ffill().fillna(0).astype('int32')

例子

以下是代码−

import pandas as pd

# 创建pandas dataframe
df = pd.DataFrame({'One': [-3, 7, 4, 0],'two': [-6, -1, 2, -8]})

# 显示数据框
print"DataFrame: \n",df

# 遮盖
df = df.mask(df.lt(0)).ffill().fillna(0).astype('int32')

# 显示更新的DataFrame
print"\nUpdated DataFrame: \n",df

输出

这将产生以下输出−

DataFrame:
   One   two
0   -3   -6
1    7   -1
2    4    2
3    0   -8
Updated DataFrame:
   One   two
0    0    0
1    7    0
2    4    2
3    0    2

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程