有条件地替换 pandas 数据框列中的值

编程入门 行业动态 更新时间:2024-10-08 03:27:51
本文介绍了有条件地替换 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 数据框列中的值

本文发布于:2023-11-22 08:07:26,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1616615.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:有条件   数据   pandas   框列中

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!