根据多种条件替换 pandas 数据框中的值 [英] Replacing values in a pandas dataframe based on multiple conditions

查看:107
本文介绍了根据多种条件替换 pandas 数据框中的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基于此示例代码,我有一个相当简单的问题:

  x1 = 10 * np.random.randn(10 ,3)
df1 = pd.DataFrame(x1)

我正在寻找一个从 df1 导出的DataFrame,其中正值替换为 up ,负值替换为向下 0 值(如果有)替换为。我尝试使用 .where() .mask()方法,但无法获得所需的结果。 / p>

我看到其他帖子会同时根据多种条件进行过滤,但它们并未显示如何根据不同条件替换值。

解决方案

通常,您可以对值使用 np.select 并重建 DataFrame

 导入熊猫as pd 
import numpy as np

df1 = pd.DataFrame(10 * np.random.randn(10,3))
df1.iloc [0,0] = 0#因此我们可以检查== 0条件

conds = [df1.values< 0,df1.values> 0]
options = ['down','up']

pd.DataFrame(np.select(conds,options,default ='zero'),
index = df1.index,
列= df1.columns)



输出:



  0 1 2 
0零向下
1向上向下
2向上向上
3向下向下
4向上向上
5向上向上
6向上向下
7向上向下
8向下向上
9向上下降


I have a fairly simple question based on this sample code:

x1 = 10*np.random.randn(10,3)
df1 = pd.DataFrame(x1)

I am looking for a single DataFrame derived from df1 where positive values are replaced with "up", negative values are replaced with "down", and 0 values, if any, are replaced with "zero". I have tried using the .where() and .mask() methods but could not obtain the desired result.

I have seen other posts which filter according to multiple conditions at once, but they do not show how to replace values according to different conditions.

解决方案

In general, you could use np.select on the values and re-build the DataFrame

import pandas as pd
import numpy as np

df1 = pd.DataFrame(10*np.random.randn(10, 3))
df1.iloc[0, 0] = 0 # So we can check the == 0 condition 

conds = [df1.values < 0 , df1.values > 0]
choices = ['down', 'up']

pd.DataFrame(np.select(conds, choices, default='zero'),
             index=df1.index,
             columns=df1.columns)

Output:

      0     1     2
0  zero  down    up
1    up  down    up
2    up    up    up
3  down  down  down
4    up    up    up
5    up    up    up
6    up    up  down
7    up    up  down
8  down    up  down
9    up    up  down

这篇关于根据多种条件替换 pandas 数据框中的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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