Python ValueError:列的长度必须与中的键相同

Python ValueError:列的长度必须与中的键相同,python,pandas,Python,Pandas,我有下面的df Cost,Reve 0,3 4,0 0,0 10,10 4,8 len(df['Cost']) = 300 len(df['Reve']) = 300 我需要划分df['Cost']/df['Reve'] 下面是我的代码 df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric) 我得到了错误ValueError:列的长度必须与键的长度相同 df['C/R'

我有下面的df

    Cost,Reve
    0,3
    4,0
    0,0
    10,10
    4,8

len(df['Cost']) = 300

len(df['Reve']) = 300

我需要划分
df['Cost']/df['Reve']

下面是我的代码

df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric)
我得到了错误
ValueError:列的长度必须与键的长度相同

df['C/R'] = df[['Cost']].div(df['Reve'].values, axis=0)

我得到了错误
ValueError:传递的项目数错误2,位置意味着1

问题是列名称重复,请验证:

#generate duplicates
df = pd.concat([df, df], axis=1)
print (df)
  Cost Reve Cost Reve
0    0    3    0    3
1    4    0    4    0
2    0    0    0    0
3   10   10   10   10
4    4    8    4    8

df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric)
print (df)
# ValueError: Columns must be same length as key
您可以找到以下列名称:

print (df.columns[df.columns.duplicated(keep=False)])
Index(['Cost', 'Reve', 'Cost', 'Reve'], dtype='object')
如果可以通过以下方式删除列中的相同值:

df = df.loc[:, ~df.columns.duplicated()]
df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric)

#simplify division
df['C/R'] = df['Cost'].div(df['Reve'])
print (df)
   Cost  Reve  C/R
0     0     3  0.0
1     4     0  inf
2     0     0  NaN
3    10    10  1.0
4     4     8  0.5

这回答了你的问题吗?