执行以下合并
import pandas as pd
s = pd.Series(range(5, 10), index=range(10, 15), name='score')
df = pd.DataFrame({'id': (11, 13), 'value': ('a', 'b')})
pd.merge(s, df, 'left', left_index=True, right_on='id')
导致这个数据框:
score id value
NaN 5 10 NaN
0.0 6 11 a
NaN 7 12 NaN
1.0 8 13 b
NaN 9 14 NaN
为什么 Pandas 将右侧数据帧的索引作为结果的索引,而不是左侧系列的索引,即使我同时指定了左侧合并和
left_index=True
? documentation说left: use only keys from left frame
我对它的解释与我实际得到的结果不同。我所期望的是以下数据框。
score id value
10 5 10 NaN
11 6 11 a
12 7 12 NaN
13 8 13 b
14 9 14 NaN
我正在使用 Python 3.7.5 和 Pandas 0.25.3。
最佳答案
这是发生的事情:
[0, 1]
. float
要设置索引,只需分配给它:
s2 = pd.merge(s, df, how='left', left_index=True, right_on='id')
s2.index = s.index
score id value
10 5 10 NaN
11 6 11 a
12 7 12 NaN
13 8 13 b
14 9 14 NaN
您也可以在
s
上合并(只是因为我不喜欢直接调用pd.merge
):(s.to_frame()
.merge(df, how='left', left_index=True, right_on='id')
.set_axis(s.index, axis=0, inplace=False))
score id value
10 5 10 NaN
11 6 11 a
12 7 12 NaN
13 8 13 b
14 9 14 NaN
关于python - 与 Pandas 合并后设置索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59293626/