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>(Your code is missing a parenthesis at the end of <code>nscap(df_joined["NS"]</code>.)</p>

<p>As @EdChum and @TheLaughingMan write, <code>clip_upper</code> is what you want here. This answer just addresses the direct reason for the error you're getting. </p>

<p>In the function</p>

<pre><code>def nscap(ns):
    if ns &lt;= 13:
        x = ns
    elif ns &gt; 13:
        x = 13
    return x
</code></pre>

<p>effectively, <code>ns &lt;= 13</code> operations on a <code>numpy.ndarray</code>. When you compare such an array to a scalar, broadcasting takes place, and the result is an array where each element indicates whether it was true for it or not. </p>

<p>So</p>

<pre><code>if ns &lt;= 13:
</code></pre>

<p>translates to something like</p>

<pre><code>if numpy.array([True, False, True, True]):
</code></pre>

<p>and it's impossible to understand whether this is true or not. That's the error you're getting: you need to specify whether you mean if <em>all</em> entries are true, if <em>some</em> entry is true, and so on.</p>

python python-2.7 csv pandas