小编pol*_*lot的帖子

如何映射到熊猫中一列列表中的值

我有以下场景。

import pandas as pd

d = {'col1': [1, 2, 3], 'col2': [['apple'], [], ['romaine', 'potatoes']}
df = pd.DataFrame(data=d)
Run Code Online (Sandbox Code Playgroud)

所以数据框是:

   col1   col2
0   1     [apple]
1   2     []
2   3     [romaine, potatoes]
Run Code Online (Sandbox Code Playgroud)

我还有一本字典:

my_dict = {"apple" : "fruit", "potatoes" : "vegetable", "romaine" : "lettuce"}
Run Code Online (Sandbox Code Playgroud)

我想创建另一列“col3”,它将包含上面 my_dict 中的值列表:

   col1   col2                 col3
0   1     [apple]              [fruit]
1   2     []                   []
2   3     [romaine, potatoes]  [lettuce, vegetable]
Run Code Online (Sandbox Code Playgroud)

我想使用apply、map、lambda编写一行代码来实现这一点:

df["col3"] = df.col2.apply(map(lambda x: pass if not x else condition_dict[x]))
Run Code Online (Sandbox Code Playgroud)

我真的被困住了,想知道是否有可能不编写单独的函数然后作为参数传递来应用。

python lambda dictionary pandas data-science

3
推荐指数
1
解决办法
87
查看次数

标签 统计

data-science ×1

dictionary ×1

lambda ×1

pandas ×1

python ×1