python - 将值从字典添加到新列,其键与数据帧的索引匹配

标签 python pandas

我有一本字典,例如,看起来像

{'a': 1, 'b': 4, 'c': 7}

我有一个数据框,其索引值与该字典中的键相同。

我想将字典中的每个值添加到数据帧中。

我觉得对 DF 的每一行进行检查,检查索引值,将其与字典中的值进行匹配,然后尝试添加它会是一种非常慢的方式,对吗?

最佳答案

您可以使用map并分配回新列:

d = {'a': 1, 'b': 4, 'c': 7}
df = pd.DataFrame({'c':[1,2,3]},index=['a','b','c'])

df['new_col'] = df.index.map(d)

打印:

   c  new_col
a  1        1
b  2        4
c  3        7

关于python - 将值从字典添加到新列,其键与数据帧的索引匹配,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74476226/

相关文章:

python - (Python,数据帧): Record the average of all numbers in a column that are smaller than the n'th percentile

python - 使用 for 循环创建数据副本

python - 比较两个 pandas 数据帧的内容,即使行的顺序不同

python - 在 Python Pandas 中将 GZIP 压缩应用于 CSV

python - 从 pandas DataFrame 中选择行 : only rows with at least three ones need to be selected

pandas - 提取第一列数据并根据第一列数据更新第二列

python-3.x - 如何使用列表中的每个值重复数据框中的行?

python - 检查 python 中的邮资模式

python - scipy.misc.imread 创建一个没有大小或形状的图像

python - 如何抓取所有 ID 具有不同值的所有 <li id=> ?