Heisenberg
Heisenberg

Reputation: 5299

How to make dtype converter function in Pandas?

I would like to make functions and pass pipe or apply method in pandas to avoid recursive assignment and for practice.

Here is my example dataframe.

A
0 1
1 2
2 3
3 4

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

def converter(df,cols,types):
df.cols=df.cols.astype(types)
return df

then pass to pipe method.

df.pipe(converter,cols=df.A,types="str")

but it causes an error.

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

How can I avoid this kind of error?

Upvotes: 1

Views: 650

Answers (1)

jezrael
jezrael

Reputation: 862691

You need add [] for select columns:

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

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

def converter(df,cols,types):
    df[cols]=df[cols].astype(types)
    return df

print (converter(df, 'A', float))    
     A
0  1.0
1  2.0
2  3.0
3  4.0

Upvotes: 1

Related Questions