ValueError: 不能为指标列使用现有列的名称

Tan*_*rza 2 python pandas

我需要解决一个问题,我将有一个数据框,比如 df,名称和年龄,我需要在 for 循环中生成另一个带有名称和性别的数据框,我需要将 for 循环中生成的数据框与 df 合并在df中获取性别。所以我在解决我的问题之前尝试了下面的代码

import pandas as pd
d = {'Age': [45, 38], 'Name': ['John', 'Emily']}
df = pd.DataFrame(data=d)
d1={'Gender':['M'],'Name':['John']}
df1=pd.DataFrame(data=d1)

df3 = df.merge(df1, on=['Name'], how='left', indicator=True)
df3

d2={'Gender':['F'],'Name':['Emily']}
df4=pd.DataFrame(data=d2)
df5=df3.merge(df4, on=['Name'], how='left', indicator=True)
Run Code Online (Sandbox Code Playgroud)

运行最后一行时出现以下错误。

 "Cannot use name of an existing column for indicator column")

ValueError: Cannot use name of an existing column for indicator column
Run Code Online (Sandbox Code Playgroud)

你能建议我如何在 python 3.x 中解决这个问题吗?

Ore*_*shi 5

有更好的方法来完成你想要做的事情(正如另一个人回答的那样)。但要了解为什么会出现错误,请阅读以下内容。

因为您进行了一次合并,所以您现在_merge在 df3.conf 文件中有一个名为的列。当您再次合并时,您无法再创建另一个_merge.

顺便说indicator=True一句,供将来参考,现在您有,但也可以传入一个字符串,例如indicator='exists'Then 您的“指示”您加入方式的新列将被调用exists,您可以通过执行选择它df5['exists']

看看这个简单的例子并在一个 repl

>>> df1
  col1 col2
0    a    b
1    b    c
2    d    e
>>> df2
  col1 col2
0    a    b
1    b    c
>>> df1.merge(df2, on='col1', how='left', indicator=True)
  col1 col2_x col2_y     _merge
0    a      b      b       both
1    b      c      c       both
2    d      e    NaN  left_only
>>> df3 = df1.merge(df2, on='col1', how='left', indicator=True)
>>> df4 = pd.DataFrame([['d', 'e']], columns=['col1', 'col2'])
>>> df3.merge(df4, on='col1', how='left', indicator=True)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/devtools/uat/anaconda4321/lib/python3.6/site-packages/pandas/core/frame.py", line 4722, in merge
copy=copy, indicator=indicator)
  File "/usr/local/devtools/uat/anaconda4321/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 54, in merge
return op.get_result()
  File "/usr/local/devtools/uat/anaconda4321/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 567, in get_result
self.left, self.right)
  File "/usr/local/devtools/uat/anaconda4321/lib/python3.6/site-packages/pandas/core/reshape/merge.py", line 605, in _indicator_pre_merge
"Cannot use name of an existing column for indicator column")
ValueError: Cannot use name of an existing column for indicator column
>>> df3.merge(df4, on='col1', how='left', indicator='exists')
  col1 col2_x col2_y     _merge col2     exists
0    a      b      b       both  NaN  left_only
1    b      c      c       both  NaN  left_only
2    d      e    NaN  left_only    e       both
Run Code Online (Sandbox Code Playgroud)