有条件地替换 pandas 数据框列中的值 [英] Conditional Substitution of values in pandas dataframe columns

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

问题描述

假设我有一个pandas数据框,其列值像df.age = {25,35,76,21,23,30}这样的年龄

suppose I've a pandas dataframe with column values as age like this df.age = {25, 35, 76, 21, 23, 30}

我想像这样进行就地替换:

I want to do an inplace replace like this:

如果df.age> = 25且df.age< = 35: 将该值替换为1 别的: 将该值替换为0

if df.age >=25 and df.age <= 35: replace that value with 1 else: replace that value with 0

我已经尝试过df [df.age> = 7.35和df.age< = 7.45,'age'] = 0 但似乎不起作用.

I've tried this df[df.age >= 7.35 and df.age <= 7.45, 'age'] = 0 but doesn't seem to work.

推荐答案

您还可以创建一个函数来检查您的条件并将其应用于数据框:

You can also create a function to check your conditions, and apply to the dataframe:

def condition(value):
    if 25 <= value <= 35:
        return 1
    return 0

# stealing sample from @AnandSKumar because I'm lazy
In [32]: df
Out[32]: 
   age
0   25
1   35
2   76
3   21
4   23
5   30

In [33]: df['age'] = df['age'].apply(condition)

In [34]: df
Out[34]: 
   age
0    1
1    1
2    0
3    0
4    0
5    1


或使用带有lambda的衬纸:


Or using one liner with lambda:

df['age'] = df['age'].apply(lambda x: 1 if 25 <=  x <= 35 else 0)

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

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