Writing variable sized arrays to Pandas cells
<p>I have a large data set and I want to do a convolution calculation using multiple rows that match a criteria. I need to calculate a vector for each row first, and I thought it would be more efficient to store my vector in a dataframe column so I could try and avoid a for loop when I do the convolution. Trouble is, the vectors are variable length and I can't figure out how to do it.</p>

<p>Here's a summary of my data:</p>

<pre><code>Date        State  Alloc P
2012-01-01  AK     3     0.5
2012-01-01  AL     4     0.3
â¦
</code></pre>

<p>Each state has a different Alloc and P value. Thereâs a row for every date and state and my dataframe is over 15,000 rows long.</p>

<p>For each entry, I want a vector that looks like this:</p>

<pre><code>[P, np.zeros(Alloc), 1-P]
</code></pre>

<p>I can't figure out how to set a new column like this. I've tried statements like:</p>

<pre><code>df['Test'] = [df['P'], np.zeros(df['Alloc'), 1 â df['P']]
</code></pre>

<p>but they don't work.</p>

<p>Does anyone have any ideas?</p>

<p>Thanks âº</p>

<p>So here's the answer. <a href="http://stackoverflow.com/users/2336654/pirsquared">piRSquared</a> was almost right, but not quite. There are several parts here.</p>

<p>The apply method partially works. It passes a row to the function and you can do a calculation as shown above. The problem is, you get a "ValueError: Shape of passed values is..." error message. The number of columns returned doesn't match the number of columns in the dataframe. My guess is this is because the return value is a list and Pandas isn't interpreting the result correctly. </p>

<p>The workaround is to do the apply on a single column. This single column should contain the P value and Alloc value. Here are the steps:</p>

<p>Create the merged column:</p>

<pre><code>df['temp'] = df[['P','Alloc']].values.tolist()
</code></pre>

<p>Write a function:</p>

<pre><code>def array_p(x): return [x[0]] + [0]*int(x[1]) + [1 - x[0]]
</code></pre>

<p>(int is needed because the previous line gives floats. I didn't need np.zeros)</p>

<p>Apply the function:  </p>

<pre><code>df['Array'] = temp['temp'].apply(array_p)
</code></pre>

<p>This works, but obviously involves more steps than it should. If anyone can provide a better answer, I'd love to hear it.</p>

python pandas