How to make dtype converter function in Pandas?
<p>I would like to make functions and pass pipe or apply method in <code>pandas</code> to avoid recursive assignment and for practice.</p>

<p>Here is my example dataframe.</p>

<pre><code>A
0 1
1 2
2 3
3 4
</code></pre>

<p>And I defined my converter function,to pass pipe method.</p>

<pre><code>def converter(df,cols,types):
df.cols=df.cols.astype(types)
return df
</code></pre>

<p>then pass to pipe method.</p>

<pre><code>df.pipe(converter,cols=df.A,types="str")
</code></pre>

<p>but it causes an error.</p>

<blockquote>
  <p>AttributeError:'DataFrame' object has no attribute 'cols'</p>
</blockquote>

<p>How can I avoid this kind of error?</p>

<p>You need add <code>[]</code> for select columns:</p>

<pre><code>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
</code></pre>

python pandas indexing dataframe casting