为了账号安全,请及时绑定邮箱和手机立即绑定

如何在 Pandas 合并中指定分层列?

如何在 Pandas 合并中指定分层列?

MMMHUHU 2023-12-29 15:09:29
on在对in 的工作方式产生严重误解之后join(剧透:与onin非常不同merge),这是我的示例代码。import pandas as pdindex1 = pd.MultiIndex.from_product([["variables"], ["number", "fruit"]])df1 = pd.DataFrame([["one", "apple"], ["two", "banana"]], columns=index1)index2 = pd.MultiIndex.from_product([["variables"], ["fruit", "color"]])df2 = pd.DataFrame([["banana", "yellow"]], columns=index2)print(df1.merge(df2, on="fruit", how="left"))我得到一个KeyError. 我如何variables.fruit在这里正确引用?要理解我的目的,请考虑没有多重索引的相同问题:import pandas as pddf1 = pd.DataFrame([["one", "apple"], ["two", "banana"]], columns=["number", "fruit"])df2 = pd.DataFrame([["banana", "yellow"]], columns=["fruit", "color"])# this is obviously incorrect as it uses indexes on `df1` as well as `df2`:print(df1.join(df2, rsuffix="_"))# this is *also* incorrect, although I initially thought it should work, but it uses the index on `df2`:print(df1.join(df2, on="fruit", rsuffix="_"))# this is correct:print(df1.merge(df2, on="fruit", how="left"))预期和想要的结果是这样的:  number   fruit   color0    one   apple     NaN1    two  banana  yellowfruit当是多重索引的一部分时,如何获得相同的结果?
查看完整描述

1 回答

?
SMILET

TA贡献1796条经验 获得超4个赞

我想我明白你现在想要实现的目标,但我认为这不会join让你实现这一目标。和DataFrame.join都DataFrame.merge可以调用pandas.core.reshape.merge.merge,但使用DataFrame.merge可以让您更好地控制应用的默认值。


在您的情况下,您可以使用引用列来通过元组列表加入,其中元组的元素是多索引列的级别。即要使用variables / fruit列,可以通过[('variables', 'fruit')].


使用元组是索引多索引列(和行索引)的方式。您需要将其包装在列表中,因为可以使用多个列或多个多索引列来执行合并操作,就像 SQL 中的 JOIN 语句一样。传递单个字符串只是一个方便的情况,它会为您包装在列表中。


由于您仅加入 1 列,因此它是单个元组的列表。


import pandas as pd


index1 = pd.MultiIndex.from_product([["variables"], ["number", "fruit"]])

df1 = pd.DataFrame([["one", "apple"], ["two", "banana"]], columns=index1)


index2 = pd.MultiIndex.from_product([["variables"], ["fruit", "color"]])

df2 = pd.DataFrame([["banana", "yellow"]], columns=index2)


df1.merge(df2, how='left', on=[('variables', 'fruit')])

# returns:

  variables

     number   fruit   color

0       one   apple     NaN

1       two  banana  yellow


查看完整回答
反对 回复 2023-12-29
  • 1 回答
  • 0 关注
  • 40 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信