所以我最近尝试开始使用Jupyter笔记本,因为我发现它们比在代码文件中保留冗长的注释要方便得多。
据说要测试基本功能,我想模拟移动平均线。但是,正如标题所述,我什至无法使用Pandas索引方法创建一个新列(该方法对我有用)。
这是我使用的代码:
import pandas as pd
from pandas_datareader import data as pdr
import matplotlib.pyplot as plt
from datetime import datetime
%matplotlib inline
fb = pdr.DataReader("FB","yahoo",datetime(2012,5,12),datetime(2020,5,25))
fb['MA10'] = fb['Close'].rolling(10).mean()
最后一行是生成错误(TypeError: 'NoneType' object is not iterable
的原因,该错误源于我调用fb['MA10']
的原因,因为我在运行代码的右侧没有遇到任何问题。我很沮丧,希望得到您的反馈,我已经在下面张贴了完整的Error Traceback,供有兴趣的人参考。
编辑
我仅输入fb['MA10'] = fb['Close']
时会收到错误消息,而fb['Close']=fb['Open']
不会产生问题,因为两者都是现有列,但是我不想每次都手动创建一个新列。
--------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-55-fa34c8084387> in <module>
1 fb = pdr.DataReader("FB","yahoo",datetime(2012,5,12),datetime(2020,5,25))
----> 2 type(fb['MA10'])
c:\users\robjr\appdata\local\programs\python\python38\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2777
2778 # Do we have a slicer (on rows)?
-> 2779 indexer = convert_to_index_sliceable(self, key)
2780 if indexer is not None:
2781 # either we have a slice or we have a string that can be converted
c:\users\robjr\appdata\local\programs\python\python38\lib\site-packages\pandas\core\indexing.py in convert_to_index_sliceable(obj, key)
2276 if idx._supports_partial_string_indexing:
2277 try:
-> 2278 return idx._get_string_slice(key)
2279 except (KeyError, ValueError, NotImplementedError):
2280 return None
c:\users\robjr\appdata\local\programs\python\python38\lib\site-packages\pandas\core\indexes\datetimes.py in _get_string_slice(self, key, use_lhs, use_rhs)
776 def _get_string_slice(self, key: str, use_lhs: bool = True, use_rhs: bool = True):
777 freq = getattr(self, "freqstr", getattr(self, "inferred_freq", None))
--> 778 _, parsed, reso = parsing.parse_time_string(key, freq)
779 loc = self._partial_date_slice(reso, parsed, use_lhs=use_lhs, use_rhs=use_rhs)
780 return loc
pandas\_libs\tslibs\parsing.pyx in pandas._libs.tslibs.parsing.parse_time_string()
pandas\_libs\tslibs\parsing.pyx in pandas._libs.tslibs.parsing.parse_datetime_string_with_reso()
pandas\_libs\tslibs\parsing.pyx in pandas._libs.tslibs.parsing.dateutil_parse()
TypeError: 'NoneType' object is not iterable
答案 0 :(得分:1)
您需要处理丢失的值,请尝试
fb['MA10'] = fb['Close'].fillna(0).rolling(10).mean()