Append a column to a dataframe in Pandas
<p>I am trying to append a numpy.darray to a dataframe with little success.
The dataframe is called user2 and the numpy.darray is called CallTime.</p>

<p>I tried:</p>

<pre><code>user2["CallTime"] = CallTime.values
</code></pre>

<p>but I get an error message:</p>

<pre><code>Traceback (most recent call last):
File "&lt;ipython-input-53-fa327550a3e0&gt;", line 1, in &lt;module&gt;
user2["CallTime"] = CallTime.values
AttributeError: 'numpy.ndarray' object has no attribute 'values'
</code></pre>

<p>Then I tried:</p>

<pre><code>user2["CallTime"] = user2.assign(CallTime = CallTime.values)
</code></pre>

<p>but I get again the same error message as above.</p>

<p>I also tried to use the merge command but for some reason it was not recognized by Python although I have imported pandas.  In the example below CallTime is a dataframe:</p>

<pre><code> user3 = merge(user2, CallTime)
</code></pre>

<p>Error message:</p>

<pre><code>  Traceback (most recent call last):
  File "&lt;ipython-input-56-0ebf65759df3&gt;", line 1, in &lt;module&gt;
  user3 = merge(user2, CallTime)
  NameError: name 'merge' is not defined
</code></pre>

<p>Any ideas?</p>

<p>Thank you!</p>

<p><code>pandas DataFrame</code> is a 2-dimensional data structure, and each column of a <code>DataFrame</code> is a 1-dimensional <code>Series</code>. So if you want to add one column to a DataFrame, you must first convert it into <code>Series</code>. np.ndarray is a multi-dimensional data structure. From your code, I believe the shape of np.ndarray <code>CallTime</code> should be <code>nx1</code> (<code>n</code> rows and <code>1</code> colmun), and it's easy to convert it to a Series. Here is an example:</p>

<pre><code>df = DataFrame(np.random.rand(5,2), columns=['A', 'B'])
</code></pre>

<p>This creates a dataframe <code>df</code> with two columns 'A' and 'B', and <code>5</code> rows.</p>

<pre><code>CallTime = np.random.rand(5,1)
</code></pre>

<p>Assume this is your <code>np.ndarray</code> data <code>CallTime</code></p>

<pre><code>df['C'] = pd.Series(CallTime[:, 0])
</code></pre>

<p>This will add a new column to <code>df</code>. Here <code>CallTime[:,0]</code> is used to select first column of <code>CallTime</code>, so if you want to use different column from <code>np.ndarray</code>, change the index.</p>

<p>Please make sure that the number of rows for <code>df</code> and <code>CallTime</code> are equal.</p>

<p>Hope this would be helpful.</p>

python numpy