python - 如何根据 Pandas 中第一个数据帧中的某些列值添加第二个数据帧中的列值

标签 python pandas

我的第一个数据框是这样的:

RowCol  Value_Pre
Key1 234
Key3 235
Key2 235
Key4 237

我的第二个数据框是:

RowCol  Value_Post
Key3 235
Key1 334
Key4 237
Key2 435

如何通过组合两个数据帧来创建第三个数据帧(如下所示)

RowCol  Value_Pre Value_Post
Key1 	234	334
Key3	235	235
Key2	235	435
Key4	237	237

如何用 Python 开发此代码?

最佳答案

使用map :

df1['Value_Post'] = df1['RowCol'].map(df2.set_index('RowCol')['Value_Post'])
print (df1)
  RowCol  Value_Pre  Value_Post
0   Key1        234         334
1   Key3        235         235
2   Key2        235         435
3   Key4        237         237

或者merge使用左连接,特别是在必要时附加多个新列:

df = df1.merge(df2, on='RowCol', how='left')

关于python - 如何根据 Pandas 中第一个数据帧中的某些列值添加第二个数据帧中的列值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52966472/

相关文章:

python - Pandas 数据帧 : Replace based on filter and regex extract

python - Pandas 构建在 Django AWS Elastic Beanstalk 部署上失败

python - 在 python 模块中测试示例代码

python - 在 Pandas 中,如何按键中的每 N 行进行分组,保存一列的最后一个值并根据 'set' 中的所有行计算另一列?

python - 在嵌套列表上使用 for 循环执行列

python - 基于numpy数组从多索引数据框中获取数据

python - 根据 Python Pandas 中的条件减去两行

python - 我想获取不包括零的行的最小数字索引

python - 使用数据框中多行的信息创建新变量

python - Pandas (Python) - 将数据分段为时间范围