Miyashita Hikaru Miyashita Hikaru - 1 year ago 191
Python Question

How to make dtype converter function in Pandas?

I would like to make functions and pass pipe or apply method in

to avoid recursive assignment and for practice.

Here is my example dataframe.

0 1
1 2
2 3
3 4

And I defined my converter function,to pass pipe method.

def converter(df,cols,types):
return df

then pass to pipe method.


but it causes an error.

AttributeError:'DataFrame' object has no attribute 'cols'

How can I avoid this kind of error?

Answer Source

You need add [] for select columns:

df = pd.DataFrame({'A':[1,2,3,4]})

print (df)
0  1
1  2
2  3
3  4

def converter(df,cols,types):
    return df

print (converter(df, 'A', float))    
0  1.0
1  2.0
2  3.0
3  4.0
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download