【问题标题】:AttributeError: 'Series' object has no attribute 'items'AttributeError:“系列”对象没有属性“项目”
【发布时间】:2015-10-05 08:17:51
【问题描述】:

我正在尝试使用同事编写的脚本。

这部分脚本运行良好:

xl = pd.ExcelFile(path + WQ_file)
sheet_names = xl.sheet_names

df = pd.read_excel(path + WQ_file, sheetname = 'Chemistry Output Table', skiprows = [0,1,2,4,5,6,7], 
               index_col = [0,1], na_values = ['', 'na', '-'])
df.index.names = ['Field_ID', 'Date_Time']

header = pd.read_excel(path + WQ_file, sheetname = 'header data',  
               index_col = [0], na_values = ['', 'na', ' - '])
header_dict = {ah: header['name_short'].loc[ah] for ah in header.index}

analytes_excel = pd.read_excel(path + WQ_file, sheetname = 'analytes', columns = 'name')
analytes_list = [item for sublist in analytes_excel.values.tolist() for item in sublist]
analytes = [header['name_short'].loc[x] for x in analytes_list]    

但这部分不是:

# Clean up the data and report "less than" as half of the LOR
df2 = df.copy()
for col in df2.columns:
x = []
for (a, b) in df2[col].items():
    if b == " - ":
        b = np.nan
    try:
        b = float(b)
    except:
        b = float(b.strip('< '))/2
    x.append(b)
df2[col] = x

我收到以下错误:

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-4-80ad8c096fc0> in <module>()
  4 for col in df2.columns:
  5     x = []
 ----> 6     for (a, b) in df2[col].items():
  7         if b == " - ":
  8             b = np.nan

 C:\Users\SardellaC\AppData\Local\Continuum\Anaconda\lib\site-packages\pandas\core\generic.pyc in __getattr__(self, name)
 1938 
 1939         if name in self._internal_names_set:
-> 1940             return object.__getattribute__(self, name)
 1941         elif name in self._metadata:
 1942             return object.__getattribute__(self, name)

 AttributeError: 'Series' object has no attribute 'items'

这可能与使用的不同版本的 Python 有关。我对 Python 一点也不熟悉,如果有人能指出我正确的方向,我将不胜感激。

【问题讨论】:

  • df2[col] 看起来像这样:
  • Field_ID Date_Time AST2 2014-12-29 00:00:00 2.3 2014-12-29 12:00:00 NaN 2015-01-12 00:00:00 3.2 2015-01-12 15 :00:00 NaN 2015-01-28 00:00:00 2.8 2015-01-28 12:15:00 NaN 2015-01-28 12:30:00 NaN 2015-02-02 00:00:00 2.7 2015 -02-02 11:30:00 南 2015-02-03 00:00:00 2.7

标签: python python-2.7 pandas series attributeerror


【解决方案1】:

在遍历熊猫系列时使用iteritems() 而不是items()

for (a, b) in df2[col].iteritems():
    x = []
    ....

但是对于大型数据集,遍历每一行是一个非常缓慢的过程。您可以使用.apply() 函数来简化这部分代码。如果您需要简化代码,请告诉我。

【讨论】:

  • 这很好@Kathirmani Sukumar。感谢您的帮助!
猜你喜欢
  • 2020-11-18
  • 2020-11-11
  • 2019-04-22
  • 2019-07-26
  • 2020-04-04
  • 2019-09-16
  • 2017-12-12
  • 2018-05-25
  • 2019-07-07
相关资源
最近更新 更多