python-3.x - 如何根据条件(特定列的相同值)从其他数据框中复制值?

标签 python-3.x pandas dataframe conditional-statements

我有两个数据框(df1 和 df2),它们看起来像这样:

data1 = {'col1':[1,2,3,4,1,2,3,4,1,2,3,4], 'col2':np.arange(1,13)*2}

df1 = pd.DataFrame(data1)

data2 = {'x': [1,2,3,4], 'y': [10,20,40,5]}

df2 = pd.DataFrame(data2)

当 df1['col1'] 等于 df2['x'] 时,我想向 df1 添加一个新列 'col3',其值为 df2['y']。所以我的 df1 会保持这样:

col1    col2    col3
1      2      10
2      4      20
3      6      40
4      8      5
1      10     10
2      12     20
3      14     40
4      16     5
1      18     10
2      20     20
3      22     40
4      24     5

谁能帮帮我?

最佳答案

map 与从 df2 创建的字典一起使用

df1['col3'] = df1.col1.map(dict(df2[['x', 'y']].values))

df1['col3'] = df1.col1.map(dict(zip(df2.x, df2.y)))

Out[886]:
    col1  col2  col3
0      1     2    10
1      2     4    20
2      3     6    40
3      4     8     5
4      1    10    10
5      2    12    20
6      3    14    40
7      4    16     5
8      1    18    10
9      2    20    20
10     3    22    40
11     4    24     5

关于python-3.x - 如何根据条件(特定列的相同值)从其他数据框中复制值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59670123/

相关文章:

python - 在 tkinter python 中执行 ("after"脚本时如何处理无效的命令名称错误)

python - 将字节数组从\xff 转换为 x0FF

sql - 如何使用默认值将列添加到数据库

python - 如何使用Python中的现有列以其他列为条件创建新列

python - 合并和填充 Pandas DataFrames

python - 在Python中使用pandas数据框选择带有 bool 数组的行

python - pandas 中字符串到日期时间的转换

python - 如何在 QListWidget 之上添加一个 QListWidgetItem?

python - Pandas unstack 不起作用

python - 如何根据其他列中的条件将 pandas df 列中的多个值更改为 np.nan?