【发布时间】:2021-05-03 19:41:59
【问题描述】:
我有以下场景。
import pandas as pd
d = {'col1': [1, 2, 3], 'col2': [['apple'], [], ['romaine', 'potatoes']}
df = pd.DataFrame(data=d)
所以数据框是:
col1 col2
0 1 [apple]
1 2 []
2 3 [romaine, potatoes]
我还有一本字典:
my_dict = {"apple" : "fruit", "potatoes" : "vegetable", "romaine" : "lettuce"}
我想创建另一列“col3”,其中包含来自上面 my_dict 的值列表:
col1 col2 col3
0 1 [apple] [fruit]
1 2 [] []
2 3 [romaine, potatoes] [lettuce, vegetable]
我想用apply、map、lambda写一行代码来实现:
df["col3"] = df.col2.apply(map(lambda x: pass if not x else condition_dict[x]))
我真的很困惑,想知道是否可以不编写单独的函数然后作为参数传递给应用。
【问题讨论】:
标签: python pandas dictionary lambda data-science