pandas 替换类型问题 [英] Pandas replace type issue

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

问题描述

我有一个熊猫数据框,其中包含一行数据,例如:

I have a pandas dataframe with a row that contains data such as:

1 year
1 month
1 week
4 year
3 week

等等等

我正在尝试将包含月"或周"的任何内容替换为0

I am trying to replace anything that contains "month" or "week" to 0

train_df.age["weeks" in train_df.age] = 0

for i in train_df['age']:
    if "weeks" in i:
        i = "0"

似乎都不起作用.

有关如何执行此操作的任何建议? 谢谢.

Any advice on how to do this? Thanks.

推荐答案

使用str.contains:

train_df.loc[train_df['age'].str.contains(r'week|month'), 'age'] = 0

这里,我们传递一个正则表达式模式,该模式查找行是否包含星期"或月",并使用布尔掩码选择性地仅更新感兴趣的行:

Here we pass a regex pattern that looks for whether the row contains either 'week' or 'month' and use the boolean mask to selectively update just the rows on interest:

In [4]:
df.loc[df['age'].str.contains(r'week|month'), 'age'] = 0
df

Out[4]:
    age
1  year
1     0
1     0
4  year
3     0

这篇关于 pandas 替换类型问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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