我有一个熊猫数据框架,它类似于下面的,但更大更复杂
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
输出
我想基于列“string1”创建一个新列“animal”
搜索列表=['dog','cat']
如果在“搜索列表”中,则填充搜索列表中的值,否则填充“其他”
请建议如何做到这一点。多谢各位
您可以使用
str.extract()
+fillna()
:或
如果您有一个很长的列表,那么:
df
的输出:希望能对您有所帮助。谢谢
下面是一种利用内置^{} 函数及其
default
参数的方法:请注意,如果
String1
类似于"I have a dog and a cat"
,那么这将返回在search_list
中首先出现的动物相关问题 更多 >
编程相关推荐