Insert list into cells which meet column conditions
<p>Consider <code>df</code></p>

<pre><code>   A  B  C
0  3  2  1
1  4  2  3
2  1  4  1
3  2  2  3
</code></pre>

<p>I want to add another column <code>"D"</code> such that D contains different Lists based on conditions on <code>"A"</code>, <code>"B"</code> and <code>"C"</code></p>

<pre><code>   A  B  C  D
0  3  2  1  [1,0]
1  4  2  3  [1,0]
2  1  4  1  [0,2]
3  2  2  3  [2,0]
</code></pre>

<p>My code snippet looks like:</p>

<pre><code>df['D'] = 0
df['D'] = df['D'].astype(object)

df.loc[(df['A'] &gt; 1) &amp; (df['B'] &gt; 1), "D"] = [1,0]
df.loc[(df['A'] == 1) , "D"] = [0,2]
df.loc[(df['A'] == 2) &amp; (df['C'] != 0) , "D"] = [2,0]
</code></pre>

<p>When I try to run this code it throws the following error:</p>

<pre><code>ValueError: Must have equal len keys and value when setting with an iterable
</code></pre>

<p>I have converted the column into <code>Object</code> type as suggested <a href="http://stackoverflow.com/questions/26483254/python-pandas-insert-list-into-a-cell">here</a> but still with error.</p>

<p>What I can infer is that pandas is trying to iterate over the elements of the list and assigns each of those values to the cells where as I am trying to assign the entire list to all the cells meeting the criterion.</p>

<p>Is there any way I can assign lists in the above fashion?</p>

<p><strong>Disclaimer</strong>: This is my own question.</p>

<p>Both the answers provided by <a href="http://stackoverflow.com/users/2901002/jezrael">jezrael</a> and <a href="http://stackoverflow.com/users/2336654/pirsquared">piRSquared</a> work.</p>

<p>I just wanted to add another way of doing it, albeit slightly different from the requirement I posted in the question. Instead of trying to insert a <code>list</code>, you can convert the <code>list</code> into a <code>string</code> and later access it by typecasting. </p>

<pre><code>df.loc[(df['A'] &gt; 1) &amp; (df['B'] &gt; 1), "D"] = '[1,0]'
df.loc[(df['A'] == 1) , "D"] = '[0,2]'
df.loc[(df['A'] == 2) &amp; (df['C'] != 0) , "D"] = '[2,0]'
</code></pre>

<p>This may not be applicable to everyone's use, but I can definitely think of situations where this would suffice.</p>

python pandas