Python 在Pandas中将数据帧与序列合并时出现问题

Python 在Pandas中将数据帧与序列合并时出现问题,python,pandas,merge,Python,Pandas,Merge,我在熊猫合并功能方面遇到了一些棘手的问题。以下是我的问题的一个玩具示例: df1 = pd.DataFrame({'A': [0, 1, 2, 3], 'B': ['B0', 'B1', 'B2', 'B3'], 'C': ['C0', 'C1', 'C2', 'C3'], 'D': ['D0', 'D1', 'D2', 'D3']},

我在熊猫合并功能方面遇到了一些棘手的问题。以下是我的问题的一个玩具示例:

df1 = pd.DataFrame({'A': [0, 1, 2, 3],
                    'B': ['B0', 'B1', 'B2', 'B3'],
                    'C': ['C0', 'C1', 'C2', 'C3'],
                    'D': ['D0', 'D1', 'D2', 'D3']},
                     index=[0, 1, 2, 3])

s = pd.Series(['E0', 'E1', 'E2', 'E3'], index = [0,1,2,3])
如果我现在希望基于数据帧中的列A和系列中的索引将这些数据左合并,即:

pd.merge(df1,s,how='left', left_on = 'A', right_index = True)
我得到以下错误:

IndexError: list index out of range
我真的不明白。为了让事情更加混乱,用另一个数据帧替换该系列意味着一切正常:

df2 = pd.DataFrame({'E': ['E0','E1','E2','E3'],
                    'F': ['F0', 'F1', 'F2', 'F3']},
                     index=[0, 1, 2, 3])

pd.merge(df1,df2,how='left', left_on = 'A', right_index = True)
给出:

   A   B   C   D   E   F
0  0  B0  C0  D0  E0  F0
1  1  B1  C1  D1  E1  F1
2  2  B2  C2  D2  E2  F2
3  3  B3  C3  D3  E3  F3
我可能错过了一些非常基本的东西,但我怀疑这是对未来有帮助的事情之一


非常感谢。

pd.merge
希望数据帧作为其前两个参数。第二个参数不能是一个系列。但是,您可以使用
to_frame
方法将
s
转换为帧:

In [10]: pd.merge(df1, s.to_frame(), how='left', left_on='A', right_index=True)
Out[10]: 
   A   B   C   D   0
0  0  B0  C0  D0  E0
1  1  B1  C1  D1  E1
2  2  B2  C2  D2  E2
3  3  B3  C3  D3  E3
请注意,最后一列的名称是
0
。您可以通过为序列
s
指定名称来控制该列的名称:

In [15]: s.name = 'Foo'
然后最后一个列名变成
Foo

In [17]: pd.merge(df1, s.to_frame(), how='left', left_on='A', right_index=True)
Out[17]: 
   A   B   C   D Foo
0  0  B0  C0  D0  E0
1  1  B1  C1  D1  E1
2  2  B2  C2  D2  E2
3  3  B3  C3  D3  E3

没有意识到合并需要2个数据帧。非常感谢!是否需要使用
合并
?您可以指定一个系列,例如
df1['e']=s