Python Pandas Dataframe 合并并仅选择几列
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44593284/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python Pandas Dataframe merge and pick only few columns
提问by ProgSky
I have a basic question on dataframe merge. After I merge two dataframe , is there a way to pick only few columns in the result.
我有一个关于数据框合并的基本问题。在我合并两个 dataframe 之后,有没有办法只选择结果中的几列。
Taking an example from documentation
以文档为例
https://pandas.pydata.org/pandas-docs/stable/merging.html#
https://pandas.pydata.org/pandas-docs/stable/merging.html#
left = pd.DataFrame({'key1': ['K0', 'K0', 'K1', 'K2'],
'key2': ['K0', 'K1', 'K0', 'K1'],
'A': ['A0', 'A1', 'A2', 'A3'],
'B': ['B0', 'B1', 'B2', 'B3']})
right = pd.DataFrame({'key1': ['K0', 'K1', 'K1', 'K2'],
'key2': ['K0', 'K0', 'K0', 'K0'],
'C': ['C0', 'C1', 'C2', 'C3'],
'D': ['D0', 'D1', 'D2', 'D3']})
result = pd.merge(left, right, on=['key1', 'key2'])
Result comes as :
结果如下:
A B key1 key2 C D
0 A0 B0 K0 K0 C0 D0
1 A2 B2 K1 K0 C1 D1
2 A2 B2 K1 K0 C2 D2
None
Is there a way I can chose only column 'C' from 'right' dataframe? For example, I would like my result to be like:
有没有办法我只能从“正确”数据框中选择“C”列?例如,我希望我的结果是这样的:
A B key1 key2 C
0 A0 B0 K0 K0 C0
1 A2 B2 K1 K0 C1
2 A2 B2 K1 K0 C2
None
回答by Scott Boston
result = pd.merge(left, right[['key1','key2','C']], on=['key1', 'key2'])
OR
或者
right.merge(left, on=['key1','key2'])[['A','B','C','key1','key2']]