I have the following data frame, the value of the column sequence
is a list:
id sequence
001 [A, B, C, E, F]
002 [A, C]
003 []
004 [D]
I want to create two new columns called first
and second_to_last
: first
indicating the first element of the list in the sequence
column, second_to_last
indicating the second to last element of the list in the sequence
column. I am expecting the new df
to be like:
id sequence first second_to_last
001 [A, B, C, E, F] A E
002 [A, C] A A
003 [] None None
004 [D] D None
I tried to use the following code:
df['first'] = df['sequence'][0]
df['second_to_last'] = df['sequence'][-2]
But got the following errors:
There was a problem running this cell
ValueError Length of values does not match length of index
ValueErrorTraceback (most recent call last)
<ipython-input-9-f08abfd1f93c> in <module>()
----> 2 df['first'] = df['sequence'][0]
3 df['second_to_last'] = df['sequence'][-2]
4 df
/opt/conda/envs/python2/lib/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
2427 else:
2428 # set column
-> 2429 self._set_item(key, value)
2430
2431 def _setitem_slice(self, key, value):
/opt/conda/envs/python2/lib/python2.7/site-packages/pandas/core/frame.pyc in _set_item(self, key, value)
2493
2494 self._ensure_valid_index(value)
-> 2495 value = self._sanitize_column(key, value)
2496 NDFrame._set_item(self, key, value)
2497
/opt/conda/envs/python2/lib/python2.7/site-packages/pandas/core/frame.pyc in _sanitize_column(self, key, value, broadcast)
2664
2665 # turn me into an ndarray
-> 2666 value = _sanitize_index(value, self.index, copy=False)
2667 if not isinstance(value, (np.ndarray, Index)):
2668 if isinstance(value, list) and len(value) > 0:
/opt/conda/envs/python2/lib/python2.7/site-packages/pandas/core/series.pyc in _sanitize_index(data, index, copy)
2877
2878 if len(data) != len(index):
-> 2879 raise ValueError('Length of values does not match length of ' 'index')
2880
2881 if isinstance(data, PeriodIndex):
ValueError: Length of values does not match length of index
What should be the correct way of extract values for column first
and second_to_last
? Thanks!