将列表值分配给Pandas df列会产生NaN或长度错误

时间:2020-05-24 10:21:28

标签: python pandas dataframe

我有一个DataFrame

           Close    Delta   
Date            
2020-05-11  2920.50 -440    
2020-05-11  2920.25 -9      
2020-05-11  2920.25 -27     
2020-05-11  2920.50 2       
2020-05-11  2920.75 117     

现在我正在使用此功能计算“关闭”的连续增量:

tickbox = []
cumtickCount = 0

for i in range(len(df.index)):
        if df.Close[i] > df.Close[i-1]:
            cumtickCount += 1
            tickbox.append(cumtickCount)
        else:
            cumtickCount = 0

我得到了列表,但在这里我也不明白为什么值以1开头而不是0
复选框:

[1,
 1,
 2,
 3,
 1,
 2,
 3,
 4,
 5,
 6,
 1,
 1,
 2,
 3,
 4,
 5,
 6,
 7,
 8,
 9,
 1,
 2,
 3,
 4,
 5,

如果我将列表转换为df列

ct = pd.Series(tickbox)
df['consec_tick'] = ct

我得到NaN值

            Close   Delta  consec_tick
Date            
2020-05-11  2920.50 -440    NaN
2020-05-11  2920.25 -9      NaN
2020-05-11  2920.25 -27     NaN
2020-05-11  2920.50 2       NaN
2020-05-11  2920.75 117     NaN

如果我这样分配列表:

df.assign(new_col=consec_tickup)

df['consec_tick'] = consec_tickup

我收到以下错误:

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-57-9d3e9ad7ceb3> in <module>
      7             cumtickCount += 1
      8             #tickbox.append(cumtickCount)
----> 9             df['consec_tick'] = tickbox
     10         else:
     11             cumtickCount = 0

/opt/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in __setitem__(self, key, value)
   3470         else:
   3471             # set column
-> 3472             self._set_item(key, value)
   3473 
   3474     def _setitem_slice(self, key, value):

/opt/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in _set_item(self, key, value)
   3547 
   3548         self._ensure_valid_index(value)
-> 3549         value = self._sanitize_column(key, value)
   3550         NDFrame._set_item(self, key, value)
   3551 

/opt/anaconda3/lib/python3.7/site-packages/pandas/core/frame.py in _sanitize_column(self, key, value, broadcast)
   3732 
   3733             # turn me into an ndarray
-> 3734             value = sanitize_index(value, self.index, copy=False)
   3735             if not isinstance(value, (np.ndarray, Index)):
   3736                 if isinstance(value, list) and len(value) > 0:

/opt/anaconda3/lib/python3.7/site-packages/pandas/core/internals/construction.py in sanitize_index(data, index, copy)
    610 
    611     if len(data) != len(index):
--> 612         raise ValueError("Length of values does not match length of index")
    613 
    614     if isinstance(data, ABCIndexClass) and not copy:

ValueError: Length of values does not match length of index

如何正确地将'tickbox'中的值分配给该列?

1 个答案:

答案 0 :(得分:1)

您的解决方案存在一些问题,可能是由于我对目标的误解。

如果您希望该列具有与另一列相同数量的值,则需要为每个元素的tickbox添加一个值。就您而言,您没有在else分支中添加任何内容,这意味着您实际上是在跳过某些值。

另一个问题是,第一个值可能需要设置为0。相反,当i = 0时,您正在将元素0与元素-1进行比较。尝试输入代码时,我实际上得到了KeyError: -1

考虑到以上问题,我们可以重写该函数:

def consecutive_ticks(close_prices):
  # start with 0 for the first data point
  ticks = [0]
  count = 0

  # go from element 1 to the last element
  for i in range(1, len(close_prices)):
    if close_prices[i] > close_prices[i-1]:
      count += 1
    else:
      count = 0
    # we append the current count anyway.
    # it's either going to be an increment, or it's 0 if "close" is smaller
    ticks.append(count)

  return ticks

这将返回与close_prices系列相同长度的列表。因此,您可以通过以下方式简单地将其添加到数据框中:

df['consec_tick'] = consecutive_ticks(df.Close)