在Pandas中合并DataFrame和Series时出现问题

3

我在使用pandas的合并功能时遇到了一些棘手的问题。下面是一个我遇到问题的玩具示例:

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)

I get the following error:

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

我可能缺少一些非常基本的知识,但我怀疑这是那种对未来有帮助的事情之一!提前致谢。

1
你需要使用 merge 吗?你可以分配一个系列,例如 df1['E'] = s - AChampion
1个回答

3

pd.merge 需要将两个 DataFrames 作为其前两个参数。第二个参数不能是 Series。但是,您可以使用其 to_frame 方法将 s 转换为 DataFrame:

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

没意识到合并需要两个数据框。非常感谢! - Ned Yoxall

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接