可以使用pandas库的apply函数结合lambda表达式来实现按照字典中列出的条件填充新列。具体实现如下:
import pandas as pd
# 定义字典
condition_dict = {'cat': 'mammal', 'dog': 'mammal', 'crow': 'bird', 'snake': 'reptile'}
# 构造DataFrame
df = pd.DataFrame({"animal": ['cat', 'dog', 'crow', 'snake']})
# 使用apply函数结合lambda表达式填充新列
df['type'] = df['animal'].apply(lambda x: condition_dict[x])
# 打印结果
print(df)
输出结果为:
animal type
0 cat mammal
1 dog mammal
2 crow bird
3 snake reptile
其中,apply函数会将每一行的数据作为参数传递给lambda表达式进行处理,lambda表达式根据字典中给出的条件进行匹配,并返回对应的值填充新的列中。
上一篇:按照字典中的多个键对列表进行排序
下一篇:按照字典中元组的元素进行组织?