Python Pandas convert column data type
<p>I know a question like this has been asked zillion types, but so far I have not been able to find an answer to this question.</p>

<p>I have joined two .csv files together with Pandas and now I would like to add some more columns to the new joined .csv file and the values calculate based on the already available data.</p>

<p>However, I keep getting this error:</p>

<pre><code>"The truth value of a is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()."
</code></pre>

<p>Now that obviously seems to be a problem with the data type of my column (which is all integers), but I have not found a (working) way to set that column as integers.</p>

<p>Here is my code:</p>

<pre><code>import pandas

def nscap(ns):
    if ns &lt;= 13:
        x = ns
    elif ns &gt; 13:
        x = 13
    return x

df_1 = pandas.read_csv("a.csv", sep=';', names=["DWD_ID", "NS"], header=0)
df_2 = pandas.read_csv("b.csv", sep=';', names=["VEG", "DWD_ID"], header=0)
df_joined = pandas.merge(df_1, df_2, on="DWD_ID")
df_joined["NS_Cap"] = nscap(df_joined["NS"])
</code></pre>

<p>If i set</p>

<pre><code>df_joined["NS_Cap"] = nscap(20)
</code></pre>

<p>the code works fine</p>

<p>I have tried functions like .astype(int) or .to_numeric() but unless I had the syntax wrong, it didn't work for me.</p>

<p>Thanks in advance!</p>

<p>As with @EdChum's comment, you need to use <code>clip(upper=13)</code> or <code>clip_upper(13)</code>. One other option which can help you in the long run with instances like this is to use <code>apply</code> with a lambda function. This is a really nifty all-around method.</p>

<pre><code>import pandas as pd
import numpy as np

df = pd.DataFrame(np.random.randint(5,18,size=(5, 4)), columns=list('ABCD'))
nscap = lambda x: min(x, 13)

print df.head()
print '-' * 20

df['NSCAP'] = df['D'].apply(nscap)

print df.head()
</code></pre>

<p>Result:</p>

<p><a href="http://i.stack.imgur.com/HEZAF.png" rel="nofollow"><img src="http://i.stack.imgur.com/HEZAF.png" alt="enter image description here"></a></p>

<p>Take note of the last 2 lines of the second dataframe.</p>

<p>Hope this helps.</p>

python python-2.7 csv pandas