vatsal vatsal - 1 month ago 10
Python Question

ValueError In Pandas

I have a Data Frame with 15 columns suppose out of which i want only 6.
I am performing aggregate and then group by but it is throwing error.

def my_compute_function(my_input):

df=pd.DataFrame(my_input)
df2=df[(df['D'] == "Validated")]
df2[['A','E','F']]=df2[['A','E','F']].apply(pd.to_numeric)
df3=df2[['A','B','C','D','E','F']].groupby(['B','C','D']).agg({'A':
'max','E': 'max','F': 'max'}).reset_index()

return df3


So i want only 6 columns A,B,C,D,E,F.

When i am adding this line

df2[['A','E','F']]=df2[['A','E','F']].apply(pd.to_numeric)


it is throwing error that ValueError: can not infer schema from empty dataset.

Answer Source

For me it working perfectly, only .copy is necessary:

df = pd.DataFrame({
'D':['Validated','Validated','a'], 
'E':['4','8','8'], 
'A':['4','5','8'],
'F':['4','9','8'],
'B':['a','a','r'],
'C':['b','b','b']})

df2=df[(df['D'] == "Validated")].copy()
print (df2)
   A  B  C          D  E  F
0  4  a  b  Validated  4  4
1  5  a  b  Validated  8  9

#for replace ',' to '.' 
df2[['A','E','F']]=df2[['A','E','F']].replace(',','.', regex=True).apply(pd.to_numeric)
df3=df2.groupby(['B','C','D']).agg({'A':'max','E': 'max','F': 'max'}).reset_index()
print (df3)
   B  C          D  A  F  E
0  a  b  Validated  5  9  8