在对on在join中的工作方式产生了严重误解之后(剧透:与merge中的on非常不同),下面是我的示例代码。
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)
print(df1.merge(df2, on="fruit", how="left"))我得到了一个KeyError。如何在这里正确引用variables.fruit?
为了理解我想要的是什么,考虑一下没有多索引的相同问题:
import pandas as pd
df1 = 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 color
0 one apple NaN
1 two banana yellow当fruit是多索引的一部分时,我如何获得相同的结果?
发布于 2020-10-24 05:05:34
我想我理解您现在想要实现的目标,而且我认为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 yellowhttps://stackoverflow.com/questions/64506826
复制相似问题