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

2024-10-06 15:23:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个熊猫数据框架,它类似于下面的,但更大更复杂

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

输出

^{tb1}$

我想基于列“string1”创建一个新列“animal”

搜索列表=['dog','cat']

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

^{tb2}$

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


Tags: 数据import框架pandasdf列表isas
3条回答

您可以使用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')

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"

希望能对您有所帮助。谢谢

下面是一种利用内置^{}函数及其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中首先出现的动物

相关问题 更多 >