【发布时间】:2021-11-25 07:49:29
【问题描述】:
以下相关示例并没有完全得到正确答案(但很接近):Python Pandas Assign a Dictionary Value to a Dataframe Column Based on Dictionary Key
我正在寻找一种方法,最好是单行,将字典键映射到我的数据框列。如果键匹配,我们应该将每个值解包到相应的列中。
import pandas as pd
d1 = {1231: 'val1, val2, val3',
1232: 'val1a, val2a, val3a'}
df = pd.DataFrame({'key': [1231, 1232]})
df[['val1', 'val2', 'val3']] = df['key'].apply(lambda x: d1.get(x))[0].split(', ')
df
# this will map the same values repeatedly
# and will break if the index is altered or removed
【问题讨论】: