根据字符串条件为 Pandas 数据框列赋值 [英] Assign value to a pandas dataframe column based on string condition

查看:83
本文介绍了根据字符串条件为 Pandas 数据框列赋值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个数据框,

data
id  URL
1   www.pandora.com
2   m.jcpenney.com
3   www.youtube.com
4   www.facebook.com

我想根据 URL 是否包含某个特定单词的条件创建一个新列.假设它包含youtube",我希望我的列值为 youtube.所以我尝试了以下,

I want to create a new column based on a condition that if the URL contains some particular word. Suppose if it contains 'youtube', I want my column value as youtube. So I tried the following,

data['test'] = 'other'

所以一旦我们这样做了,

so once we do that we have,

data['test']
other
other
other
other

然后我尝试了这个,

data[data['URL'].str.contains("youtub") == True]['test'] = 'Youtube'
data[data['URL'].str.contains("face") == True]['test'] = 'Facebook'

虽然这运行没有任何错误,但测试列的值不会改变.它仍然只有其他所有列.当我运行此语句时,理想情况下,仅第 3 行显示更改为Youtube",第 4 行更改为Facebook".但它不会改变.谁能告诉我我在这里犯了什么错误?

Though this runs without any error, the value of the test column, doesn't change. It still has other only for all the columns. When I run this statement, ideally 3rd row alone show change to 'Youtube' and 4th to 'Facebook'. But it doesn't change. Can anybody tell me what mistake I am doing here?

推荐答案

我认为你可以使用 loc 带有由 包含:

I think you can use loc with boolean mask created by contains:

print data['URL'].str.contains("youtub")
0    False
1    False
2     True
3    False
Name: URL, dtype: bool

data.loc[data['URL'].str.contains("youtub"),'test'] = 'Youtube'
data.loc[data['URL'].str.contains("face"),'test'] = 'Facebook'
print data
   id               URL      test
0   1   www.pandora.com       NaN
1   2    m.jcpenney.com       NaN
2   3   www.youtube.com   Youtube
3   4  www.facebook.com  Facebook

这篇关于根据字符串条件为 Pandas 数据框列赋值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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