Skip to content
Advertisement

ValueError: Columns must be same length as key in pandas

i have df below

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

len(df['Cost']) = 300

len(df['Reve']) = 300

I need to divide df['Cost'] / df['Reve']

Below is my code

df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric)

I got the error ValueError: Columns must be same length as key

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

I got the error ValueError: Wrong number of items passed 2, placement implies 1

Advertisement

Answer

Problem is duplicated columns names, verify:

#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

You can find this columns names:

print (df.columns[df.columns.duplicated(keep=False)])
Index(['Cost', 'Reve', 'Cost', 'Reve'], dtype='object')

If same values in columns is possible remove duplicated by:

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
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement