【发布时间】:2018-03-29 03:46:02
【问题描述】:
我有如下数据框,sequence列的值是一个列表:
id sequence
001 [A, B, C, E, F]
002 [A, C]
003 []
004 [D]
我想创建两个名为first 和second_to_last 的新列:first 表示sequence 列中列表的第一个元素,second_to_last 表示列表中的倒数第二个元素sequence 专栏。我期待新的df 是这样的:
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
我尝试使用以下代码:
df['first'] = df['sequence'][0]
df['second_to_last'] = df['sequence'][-2]
但出现以下错误:
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
提取列first 和second_to_last 的值的正确方法应该是什么?谢谢!
【问题讨论】: