用于分类的字符串操作

String manipulation for classification

我有一个链接列表,例如:

Website
www.uk_nation.co.uk
www.nation_ny.com
www.unitednation.com
www.nation.of.freedom.es
www.freedom.org

等等。

以上是我的数据集的列的样子。 如您所见,它们的共同点是“nation”。 我想 label/group 它们并在我的数据框中添加一列以用布尔值响应(True/false;例如列:Nation? 选项:True/False)。

Website                       Nation?
www.uk_nation.co.uk           True
www.nation_ny.com             True
www.unitednation.com          True
www.nation.of.freedom.es      True
www.freedom.org               False

我需要这样做才能以更简单(并且可能更快)的方式对网站进行分类。 您对如何操作有什么建议吗?

欢迎任何帮助。

应该这样做:

df['Nation?']= df['website'].apply(lambda x: 'nation' in x.lower())

尝试str.contains

df['Nation']=df.Website.str.upper().str.contains('NATION')
0     True
1     True
2     True
3     True
4    False
Name: Website, dtype: bool

这是我的建议:

import pandas as pd

df = pd.DataFrame({'Website': ['www.uk_nation.co.uk', 
                                'www.nation_ny.com', 
                                'www.unitednation.com', 
                                'www.nation.of.freedom.es', 
                                'www.freedom.org']})

df['Nation?'] = df['Website'].str.contains("nation")
print(df)

输出:

                    Website  Nation?
0       www.uk_nation.co.uk     True
1         www.nation_ny.com     True
2      www.unitednation.com     True
3  www.nation.of.freedom.es     True
4           www.freedom.org    False