繁体   English   中英

如果列表中的字符串与另一列匹配,则创建一个 pandas 列

[英]Create an pandas column if a string from a list matches from another column

我有一个 pandas dataframe,它与下面的类似,但更大更复杂。

import pandas as pd
d = {'weight': [70, 10, 65, 1], 'String1': ['Labrador is a dog',
'Abyssinian is a cat',
'German Shepard is a dog',
'pigeon is a bird']}
df = pd.DataFrame(data=d)
df

Output

重量 细绳
0 70 拉布拉多是狗
1个 10 阿比西尼亚猫是猫
2个 65 德国牧羊犬是一只狗
3个 1个 鸽子是一只鸟

我想根据“string1”列创建一个新列“animal”

search_list = ['狗','猫']

如果在“搜索列表”中,则从搜索列表中填充值,否则填充“其他”

重量 细绳 动物
0 70 拉布拉多是狗
1个 10 阿比西尼亚猫是猫
2个 65 德国牧羊犬是一只狗
3个 1个 鸽子是一只鸟 其他

请建议如何做到这一点。 谢谢。

这是一种利用内置next function 及其default参数的方法:

In [7]: df["animal"] = df["String1"].map(lambda s: next((animal for animal in search_list if animal in s), "other"))
   ...:

In [8]: df
Out[8]:
   weight                  String1 animal
0      70        Labrador is a dog    dog
1      10      Abyssinian is a cat    cat
2      65  German Shepard is a dog    dog
3       1         pigeon is a bird  other

请注意,如果String1类似于"I have a dog and a cat" ,那么这将返回search_list中最先出现的动物。

您可以使用str.extract() + fillna()

df['animal']=df['String1'].str.extract(pat='(dog|cat)',expand=False).fillna('other')

或者

如果你有一个很长的列表,那么:

pat='('+'|'.join(search_list)+')'
df['animal']=df['String1'].str.extract(pat=pat,expand=False).fillna('other')

output 的df :

    weight  String1                     animal
0   70      Labrador is a dog           dog
1   10      Abyssinian is a cat         cat
2   65      German Shepard is a dog     dog
3   1       pigeon is a bird            other
df["animal"] = "other" # initial set
df.loc[df["String"].str.contains("dog", case=True), "animal"] = "dog"
df.loc[df["String"].str.contains("cat", case=True), "animal"] = "cat"

希望对你有所帮助。 谢谢。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM