python - 比较 pandas 数据帧,从其他数据帧捕获数据

标签 python pandas dataframe

我不太确定如何表达这个问题,但让我举个例子。我有 2 个 pandas 数据框:

import pandas as pd

data1 = [['tom', '1000', 50], ['bill', '1001', 45], ['mike', '1002', 30], ['joe', '1003', 35]]
data2 = [['1000-000', 'New York'], ['1001-000', 'Los Angeles'], ['1005-000', 'Chicago'], ['1006-000', 'Atlanta']]

df1 = pd.DataFrame(data1, columns=['name', 'id', 'age'])
df2 = pd.DataFrame(data2, columns=['id #', 'city'])

两个数据帧都有一个 id 列,我想对其进行比较。但我需要缩短 df2 的 id 列才能这样做:

df2['id shortened'] = df2['id'].str[:4]

现在我比较 df1 中的 id 列和 df2 中的 id Shorted 列:

df3 = df1[df1['id #'].isin(df2['id shortened'])]

如果我打印 df3,结果如下:

   name    id  age
0   tom  1000   50
1  bill  1001   45

这很接近,但我真正想要的是:

   name    id  age       id #
0   tom  1000   50   1000-000
1  bill  1001   45   1001-000

id # 很重要,但我不确定在比较两个数据帧时如何将其包含在结果中?

最佳答案

IIUC,你可以这样做:

df1.merge(df2.assign(id=df2['id #'].str.extract('^(.*)-')),
          on='id',
         )

输出:

   name    id  age      id #         city
0   tom  1000   50  1000-000     New York
1  bill  1001   45  1001-000  Los Angeles

关于python - 比较 pandas 数据帧,从其他数据帧捕获数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59415899/

相关文章:

python - 如何从 jsonline 文件中的每一行提取元素?

python - 为不规则间隔的数据找到最接近特定时间的每日观察

python - 从文件中读取时缺少第一行 - Python Pandas

python - 迭代 Dataframe 时的嵌套 for 循环优化

python - 使用 .map() 在 pandas DataFrame 中高效地创建额外的列

r - 如何从 R 中的多个 id 中获取独占和总计数

r - 从 R 中两个较大的 data.frame 中的任意两个同名变量中生成 `data.frame`

python - 使用 torch 视觉创建火车变换时出错

python - python中的三点相关函数

postgresql - 使用postgres替换csv文件(pandas加载数据)