np reshape within pandas apply
<p>Arise Exception: Data must be 1-dimensional.</p>

<p>I'll present the problem with a toy example to be clear.</p>

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

<p>Initial dataframe:</p>

<pre><code>df = pd.DataFrame({"A": [[10,15,12,14],[20,30,10,43]], "R":[2,2] ,"C":[2,2]})
&gt;&gt;df

       A                    C   R
0   [10, 15, 12, 14]    2   2
1   [20, 30, 10, 43]    2   2
</code></pre>

<p>Conversion to numpy array and reshape:</p>

<pre><code>df['A'] = df['A'].apply(lambda x: np.array(x))
df.apply(lambda x: print(x[0],(x[1],x[2])) ,axis=1)
df['A_reshaped'] = df.apply(lambda x[['A','R','C']]: np.reshape(x[0],(x[1],x[2])),axis=1)
df

       A                    C    R           A_reshaped
0   [10, 15, 12, 14]    2   2        [[10,15],[12,14]]
1   [20, 30, 10, 43]    2   2        [[20,30],[10,43]]
</code></pre>

<p>Someone know the reason? It seems to not accept 2 dimensional arrays in pandas cells but it's strange...</p>

<p>Thanks in advance for any help!!!</p>

<p>Using <code>apply</code> directly doesn't work - the return value is a <code>numpy</code> 2d array, and placing it back in the DataFrame confuses Pandas, for some reason. </p>

<p>This seems to work, though:</p>

<pre><code>df['reshaped'] = pd.Series([a.reshape((c, r)) for (a, c, r) in zip(df.A, df.C, df.R)])

&gt;&gt;&gt; df
                  A  C  R              reshaped
0  [10, 15, 12, 14]  2  2  [[10, 15], [12, 14]]
1  [20, 30, 10, 43]  2  2  [[20, 30], [10, 43]]
</code></pre>

python pandas numpy reshape