【问题标题】:Pandas: Pass MULTIPLE conditions in the ON parameter in pandas.mergePandas:在 pandas.merge 的 ON 参数中传递 MULTIPLE 条件
【发布时间】:2020-02-23 15:00:15
【问题描述】:

如果key match和column id不匹配,如何合并两个pandas DataFrame?

testchunck1.csv:

excel1 user_id public_key
0      Mark    key1
1      Rhonda  key2
2      Clara   key3
3      Riley   key4

testchunck2.csv:

excel2 user_id public_key
0      Ron     key2
1      Russel  key1
2      Dwyane  key2
3      Abrax   key4

输出_df:

           userid_left  public_key  userid_right
    0      Mark         key1        Russel 
    1      Rhonda       key2        Ron 
    2      Rhonda       key2        Dwyane

注意key4 在两个 DF 中匹配,但 ID(3) 相同,因此不在输出中

我的代码:

test1Excel = pd.read_csv("testchunk.csv")
test2Excel = pd.read_csv("testchunk2.csv")

df = pd.merge(test1Excel,test2Excel, on='public_key', how='inner', suffixes = ('_left','_right')).dropna()
  1. 尝试使用.filter() 过滤掉合并后的行,但是 不成功。
  2. 尝试读取 excel 的每一行以检查是否 ID匹配,但这需要很多时间。
  3. 尝试通过条件 在 on 参数本身内,但不允许这样做

因此转向 SO。

【问题讨论】:

  • 所以你要匹配,只有各自的行号不匹配,对吧?
  • 是的,没错。如果行号/id 不匹配,并且键匹配,则它在输出中。
  • 尝试使用 .filter() 过滤掉合并后的行,但不成功。 对我来说,这听起来像是一个不错的解决方案,为什么它不起作用?另外,请以其他人更容易使用的格式分享您的数据,请参阅minimal reproducible example

标签: python pandas dataframe


【解决方案1】:

试试:

df = pd.merge(test1Excel.loc[test1Excel["public_key"].str.startswith("key")].reset_index(),test2Excel.loc[test2Excel["public_key"].str.startswith("key")].reset_index(), on='public_key', how='inner', suffixes = ('_left','_right')).dropna().query("index_left!=index_right").drop(columns=["index_left", "index_right"])

输出:

  excel1 user_id_left public_key excel2 user_id_right
0      0         Mark       key1      1        Russel
1      1       Rhonda       key2      0           Ron
2      1       Rhonda       key2      2        Dwyane

【讨论】:

  • 感谢您的解决方案。我忘了提到它也匹配公钥或不以'key'开头的公钥的空值。所以我的excel大小变得太大了。我可以使用.query("str('public_key').startswith('key')") 过滤掉其中包含以“key”开头的键的行吗?
  • 我稍微调整了我的答案 - 现在你已经包含了这个额外的条件
  • 谢谢。在您更新答案之前,我实际上已经弄清楚了。在预处理步骤中,我这样做了:test1Excel = test1Excel[test1Excel['public_key'].str.startswith("key")]。但是有了这个和你的解决方案,我收到一条错误消息:ValueError: cannot mask with array containing NA / NaN values。您对此错误有任何想法吗?注意:我刚刚收到此错误,因此我尚未在线搜索。
  • 试试:test1Excel = test1Excel.loc[test1Excel['public_key'].fillna("").str.startswith("---")]
猜你喜欢
  • 2019-11-20
  • 1970-01-01
  • 2021-12-25
  • 1970-01-01
  • 2017-04-18
  • 1970-01-01
  • 2011-03-20
  • 1970-01-01
  • 2022-12-02
相关资源
最近更新 更多