python - Pandas dataframe 在不同的 dataframe 中查找一个值并赋值

标签 python python-3.x pandas dataframe

我有 2 个不同的数据框。 第一个看起来像:

     joint  label     x    z      y    pt
0        1    NaN  50.4  0.0  -8.40    10
1        2  shell  52.2  0.0  -8.40    20
2        3  shell  54.0  0.0  -8.40    30
3        4  shell  55.8  0.0  -8.40    40
4        5  shell  57.6  0.0  -8.40    50

我的第二个数据框看起来像:

     member  joint1  joint2        joint1_pt        joint2_pt
0         1       1       2                0                0
1         2       2       3                0                0
2         3       3       4                0                0
3         4       4       5                0                0

我想使用对应于特定关节的 pt 值 并将其用于第二个数据帧,因此它看起来如下所示:

     member  joint1  joint2        joint1_pt        joint2_pt
0         1       1       2                10              20
1         2       2       3                20              30
2         3       3       4                30              40
3         4       4       5                40              50

你能帮我举个例子/我应该如何处理这个问题吗? 提前致谢!!

最佳答案

你需要mapdict 创建自 Seriesset_indexto_dict正如 P-robot 中指出的那样在评论中:

d = df1.set_index('joint')['pt'].to_dict()
#mapping by Series works, but a bit slowier
#d = df1.set_index('joint')['pt']
print (d)
{1: 10, 2: 20, 3: 30, 4: 40, 5: 50}

df2['joint1_pt'] = df2['joint1'].map(d)
df2['joint2_pt'] = df2['joint2'].map(d)
print (df2)
   member  joint1  joint2  joint1_pt  joint2_pt
0       1       1       2         10         20
1       2       2       3         20         30
2       3       3       4         30         40
3       4       4       5         40         50

关于python - Pandas dataframe 在不同的 dataframe 中查找一个值并赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42419268/

相关文章:

python - pyusb:功能一次运行良好,第二次失败

Python - 可选的命令行参数

python - pytest assert_used_with 不适用于 Django 管理命令

python - 从 csv 的单元格中读取包含字典的 Pandas 数据框

python - Pandas 聚合: How to generate multiple new columns from one column and vise versa

python - 解析 JSON 时的解码问题 [python]

python - 使用数据库信息构建动态 DAG

python-3.x - 使用 Python 从 AWS S3 下载文件

python - wand - 文本换行 - 基于图像文件大小

python - 根据每个列类型获取数据框的均值和模式