python - Pandas .DataFrame : mappings a column of a list of keys to a column of the list of values

标签 python pandas dataframe

这是输入:

df = pd.DataFrame({'keys': [('K0', 'K1'), ('K1', 'K2')],
                     'A': ['A0', 'A1']})
lookup_df = pd.DataFrame({'val': ['V1', 'V2', 'V3']},
                          index = ['K0', 'K1', 'K2'])

经过一些“加入”操作后,我希望向 df 添加一个新列,该列映射 dfkeys 中的键> 到 lookup_df 中的 val

输出应该是:

pd.DataFrame({'keys': [('K0', 'K1'), ('K1', 'K2')],
              'val': [('V0', 'V1'), ('V1', 'V2')],  
              'A': ['A0', 'A1']})

我能想到的一种方法是:

df['val'] = df['keys'].apply(lambda ks: 
    list(map(lambda k: lookup_df.loc[k].val, ks)))

还有其他更好的方法来实现这一目标吗?

最佳答案

更短并避免字符串操作:

df['val'] = df['keys'].apply(pd.Series).replace(lookup_df.val).apply(tuple)

关于python - Pandas .DataFrame : mappings a column of a list of keys to a column of the list of values,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39429189/

相关文章:

python - OSError :/usr/lib/libgdal. so.20: undefined symbol :sqlite3_column_table_name

python - 如何使用python转置和删除表中的重复值?

python - 在 pd.DataFrame 中查找每 5 行的最大值

python - Pandas 将数据框写入带有附加的 Parquet 格式

python - 如何在不循环的情况下将 python JSON 行转换为数据帧列

python - pandas groupby 计数共存

python - 选择pd.Dataframe中的逆向索引

python - 获取 xml 元素的文本不起作用 : AttributeError: 'NoneType' object has no attribute 'findall'

python curl 执行带参数的命令

python-3.x - 将 NaN 文本列分离到其他数据框中