python - Pandas:如何将两列与第二个 DataFrame 合并?

标签 python pandas dataframe merge

我有一个数据框 df 包含新的 ID 而在 dfOld 中我有旧的和新的 IDs

df
   ID1new ID2new
0  5       3
1  4       2
2  3       7


dfOld

   IDold IDnew
0  33       0
1  78       1
2  65       2
3  12       3
4  24       4
5  89       5
6  77       6
7  16       7
8  69       8 

我想向 df 添加两列,其中包含 ID1newID2new 的旧 ID,所以

df1
   ID1new ID2new   ID1old   ID2old
0  5       3         89       12
1  4       2         24       65
2  3       7         12       16

我正在粗暴地做这样一个循环:

df1 = df
df1['ID1old']=0
df1['ID2old']=0
for i in net.index:
    tmp  = dfOld[dfOld.IDnew == df.ID1new[i]]
    tmp0 = dfOld[dfOld.IDnew == df.ID2new[i]]
    net.ID1old[i] = tmp.IDold[tmp.index[0]]
    net.ID1old[i] = tmp0.IDold[tmp0.index[0]]

最佳答案

您可以使用 map通过 dict dSeries s:

d = dfOld.set_index('IDnew')['IDold'].to_dict()
print (d)
{0: 33, 1: 78, 2: 65, 3: 12, 4: 24, 5: 89, 6: 77, 7: 16, 8: 69}

#s = dfOld.set_index('IDnew')['IDold']

df['ID1old'] = df.ID1new.map(d)
df['ID2old'] = df.ID2new.map(d)
print (df)
   ID1new  ID2new  ID1old  ID2old
0       5       3      89      12
1       4       2      24      65
2       3       7      12      16

关于python - Pandas:如何将两列与第二个 DataFrame 合并?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40963459/

相关文章:

python - 如何使用 Selenium 从网站下载 csv 数据

python - pip python 不在 linux 上安装模块

python - 使用 Pandas 重采样时如何获取字符串变量的模式

pandas - 如何使用元组作为查询参数之一将 pandas read_sql 从 psycopg2 迁移到 sqlalchemy

R:data.frame 中的 ne-name 因子值

pandas - Pandas 随机增加的列

python - 向量化投资组合风险

python - 如何在 xlsxWriter 中从数字单元格地址获取 Excel 格式 python

python - 新列中的部分字符串切片(或字符串拆分?)

python - Pandas 数据框错误 'StringArray requires a sequence of strings or pandas.NA'