Python - 无法循环数字Pandas

时间:2017-08-23 05:27:44

标签: python pandas dataframe

col = [];
for y in range(0, len(q)):
    df3 = df2[q.iloc[y]['ric']]
    col.append(df3[i])
q['1_quarter_return'] = col;

给了我一组可怕的错误,但是当我用数字替换y时它工作得很好,但是我需要遍历y的不同值。

错误看起来像

ValueError                                Traceback (most recent call last)
<ipython-input-55-7e9c11c3e50d> in <module>()
  3     df3 = df2[q.iloc[y]['ric']]
  4     col.append(df3[i])
----> 5 q['1_quarter_return'] = col;

/Users/dd/anaconda/lib/python2.7/site-packages/pandas/core/frame.pyc in __setitem__(self, key, value)
   2417         else:
   2418             # set column    
-> 2419             self._set_item(key, value)
   2420 
   2421     def _setitem_slice(self, key, value):

/Users/dd/anaconda/lib/python2.7/site-packages/pandas/core/frame.pyc in _set_item(self, key, value)
   2483 
   2484         self._ensure_valid_index(value)
-> 2485         value = self._sanitize_column(key, value)
   2486         NDFrame._set_item(self, key, value)
   2487 

/Users/dd/anaconda/lib/python2.7/site-packages/pandas/core/frame.pyc in _sanitize_column(self, key, value, broadcast)
   2654 
   2655             # turn me into an ndarray
-> 2656             value = _sanitize_index(value, self.index, copy=False)
   2657             if not isinstance(value, (np.ndarray, Index)):
   2658                 if isinstance(value, list) and len(value) > 0:

/Users/dd/anaconda/lib/python2.7/site-packages/pandas/core/series.pyc in _sanitize_index(data, index, copy)
   2798 
   2799     if len(data) != len(index):
-> 2800         raise ValueError('Length of values does not match length of '     'index')
   2801 
   2802     if isinstance(data, PeriodIndex):

1 个答案:

答案 0 :(得分:-1)

似乎做同样的事情,while循环工作正常,为什么这是我不确定...

col = []
y = 0;
while y < 41:
    df3 = df2[q.iloc[y]['ric']]
    col.append(df3[i])
    y = y+1;