pandas.merge()中输出列的规则

but5z9lq  于 12个月前  发布在  其他
关注(0)|答案(1)|浏览(101)

当我使用pandas.merge时,有一个奇怪的输出,我无法理解调用merge()后输出列的真实的规则。
源代码(pandas是v1.5.2):

import pandas as pd
import numpy as np

s1 = pd.Series([100, 200, 300], index=[4,5,6], name="A")
df2 = pd.DataFrame([[100,1,1,1],[200,2,2,2],[300,3,3,3]], index=[4,5,6],columns=list("ABCD"))
df3 = pd.merge(
    s1,
    df2,
    suffixes=("_left", "_right"),
    how="left",
    left_index=True,
    right_on="A",
)
print(df3)

输出为:
See the image

A  A_left  A_right   B   C   D
NaN  4     100      NaN NaN NaN NaN
NaN  5     200      NaN NaN NaN NaN
NaN  6     300      NaN NaN NaN NaN

那么问题来了,为什么第二列(标记为A)的值是输入序列的索引,而A被转换为列,而不是索引?
还有,谁能更详细地给予一下合并API的输出列的规则?
我读了docs,但它有点简短。

yrefmtwq

yrefmtwq1#

我想你误解了Series的名字:

>>> s1
4    100
5    200
6    300
Name: A, dtype: int64
#     ^--- A is the name of the values not the index

>>> s1.to_frame()
     A  # it becomes the name of the column when your convert it as DataFrame
4  100
5  200
6  300

>>> s1.rename_axis('MyIndex')
MyIndex  # now the index has a name
4    100
5    200
6    300
Name: A, dtype: int64

在代码中,您尝试查找s1的索引(没有名称)和df2的'A'列之间的关系。所以你尝试将[4,5,6]与[100,200,300]匹配,这是没有意义的。
然而,你应该做的是:

>>> pd.merge(s1, df2, on='A', how='left', suffixes=("_left", "_right"))
     A  B  C  D
0  100  1  1  1
1  200  2  2  2
2  300  3  3  3

如果你想通过索引连接,你必须用途:

>>> pd.merge(s1, df2, left_index=True, right_index=True, how='left', suffixes=("_left", "_right"))
   A_left  A_right  B  C  D
4     100      100  1  1  1
5     200      200  2  2  2
6     300      300  3  3  3

相关问题