亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在 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 關注
  • 163 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號