merge の indicator
次のコードを実行したときの出力として、正しいものを1つ選べ。
import pandas as pd
a = pd.DataFrame({"k": [1, 2]})
b = pd.DataFrame({"k": [2, 3]})
m = a.merge(b, on="k", how="outer", indicator=True)
print(sorted(m["_merge"].astype(str)))
- A
['both', 'both', 'both'] - B
['both', 'left_only', 'right_only'] - C
['left_only', 'right_only'] - D
['inner', 'left', 'right']
正解と解説を見る
正解:B
merge(indicator=True) で、結合の結果にどの表に由来するかの列が付く。結合のもれの確認に役立つ。
| 順 | 実行する行 | 実行後の変数 |
|---|---|---|
| 1 | `import pandas as pd` | — |
| 2 | `a = pd.DataFrame({"k": [1, 2]})` | a = DataFrame(2行×1列) |
| 3 | `b = pd.DataFrame({"k": [2, 3]})` | b = DataFrame(2行×1列) |
| 4 | `m = a.merge(b, on="k", how="outer", indicator…` | m = DataFrame(3行×2列), a = DataFrame(2行×1列), b = DataFrame(2行×1列) |
| 5 | `print(sorted(m["_merge"].astype(str)))` | m = DataFrame(3行×2列) |
| 結果 | 実際の出力 | ['both', 'left_only', 'right_only'] |


- A
誤り。片方にしかない行がある。
- B
正しい。
indicator=Trueで、行がどちらの表に由来するかが_merge列に入る。 - C
誤り。
k=2は両方にある。 - D
誤り。
_mergeの値はboth・left_only・right_only。
このサイトの問題は、各試験の公式に示された出題範囲に沿って作ったオリジナルの模擬問題です。本試験の問題ではありません。一般社団法人Pythonエンジニア育成推進協会の公式サービスではありません。