i have df below
JavaScript
x
12
12
1
Cost,Reve
2
0,3
3
4,0
4
0,0
5
10,10
6
4,8
7
8
len(df['Cost']) = 300
9
10
len(df['Reve']) = 300
11
12
I need to divide df['Cost'] / df['Reve']
Below is my code
JavaScript
1
2
1
df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric)
2
I got the error ValueError: Columns must be same length as key
JavaScript
1
2
1
df['C/R'] = df[['Cost']].div(df['Reve'].values, axis=0)
2
I got the error ValueError: Wrong number of items passed 2, placement implies 1
Advertisement
Answer
Problem is duplicated columns names, verify:
JavaScript
1
14
14
1
#generate duplicates
2
df = pd.concat([df, df], axis=1)
3
print (df)
4
Cost Reve Cost Reve
5
0 0 3 0 3
6
1 4 0 4 0
7
2 0 0 0 0
8
3 10 10 10 10
9
4 4 8 4 8
10
11
df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric)
12
print (df)
13
# ValueError: Columns must be same length as key
14
You can find this columns names:
JavaScript
1
3
1
print (df.columns[df.columns.duplicated(keep=False)])
2
Index(['Cost', 'Reve', 'Cost', 'Reve'], dtype='object')
3
If same values in columns is possible remove duplicated by:
JavaScript
1
13
13
1
df = df.loc[:, ~df.columns.duplicated()]
2
df[['Cost','Reve']] = df[['Cost','Reve']].apply(pd.to_numeric)
3
4
#simplify division
5
df['C/R'] = df['Cost'].div(df['Reve'])
6
print (df)
7
Cost Reve C/R
8
0 0 3 0.0
9
1 4 0 inf
10
2 0 0 NaN
11
3 10 10 1.0
12
4 4 8 0.5
13