How to add Pandas dataframe column from a element of a list in another column without lambda?
<p>Suppose I have this dataframe</p>

<pre><code>A                           B
[ 'a' , 'b' , 'c' ]         3
[ 'e' , 'f' , 'g' , 'h']    5
</code></pre>

<p>How can I create a new column such as below without lambda?</p>

<pre><code>A                                 B   C
[ 'a' , 'b' , 'c' ]               3   'b'
[ 'e' , 'f' , 'g' , 'h' ]         5   'g'
</code></pre>

<p>If using lambda, it will be</p>

<pre><code>df['C'] = df['A'].apply( lambda x : x[-2] )
</code></pre>

<p>EDIT:
Example code:</p>

<pre><code>import pandas as pd
mydata = [ { 'A' : [ 'a' , 'b' , 'c' ] ,       'B' : 3 } ,
           { 'A' : [ 'e' , 'f' , 'g' , 'h' ] , 'B' : 5}]
df = pd.DataFrame(mydata)
</code></pre>

<p>A solution is to use <code>str</code> to index from the list but it requires the string lengths to be uniform. You could also use the list comprehension proposed by Bob which is the most robust solution.</p>

<pre><code>In [110]: df.A.str.join(',').str[-3]
Out[110]:
0    b
1    g
Name: A, dtype: object
</code></pre>

<p>Here's a regex solution because this may be more robust to different string lengths and types in the list. Replace <code>"\w"</code> if actual list elements are more complex. </p>

<pre><code>#create data:
df = pd.DataFrame({'A':[['a', 'b', 'c'], ['e', 'f', 'g', 'h']], 'B': [3,5]})

#one step solution:
df['C'] = df.A.str.join(sep=',').str.extract("(\w),\w$", expand=False)

#result:
In [22]: df.C
Out[22]:
0    b
1    g
Name: C, dtype: object
</code></pre>

python pandas