簡體   English   中英

Python 3:使用數據框的字典時出現KeyError 0

[英]Python 3: KeyError 0 when using dataframe's dictionary

使用以下代碼,我試圖將n-DataFrames插入MSSQL表。

for file in os.listdir():
   print('# Inserting ' + file + ' . . .')
   df = pd.read_csv(file)
   df = df.fillna('NULL')
   if(len(df)>1):
       dfs = partDF(df , lim)
       for k in dfs.keys():
           print('\t' + str(int(k.split('t')[1])+1) + ' / ' + str(len(dfs.keys()))+ '\t')
           aux = dfs[k]
           insert2SQL(aux, table)
           del(aux)
       print(' OK :)')
   del(df, dfs)

partDF()函數將數據幀拆分為較小的數據幀,以使每個數據幀的長度均不超過1000行。 這些數據幀在字典中返回,字典的鍵名為t0,t1,t1 ... tn。
請注意,為了安全起見,我直接從dict.keys()方法中使用了鍵名。

上面的代碼在循環中插入第一個數據幀后,將引發Keyerror 0

    KeyError                                  Traceback (most recent call last)
<ipython-input-4-0e1d02aa1939> in <module>()
      8                         print('\t' + str(int(k.split('t')[1])+1) + ' / ' + str(len(dfs.keys()))+ '\t')
      9                         aux = dfs[k]
---> 10                         insert2SQL(aux, table)
     11                         del(aux)
     12                 print(' OK :)')

<ipython-input-2-fd6c30d5a003> in insert2SQL(tablilla, sqlTab)
     27         vals = list()
     28         for field in tablilla.columns:
---> 29                 if(type(tablilla[field][0]) == str):
     30                         vals.append(True)
     31                 else:

c:\python36\lib\site-packages\pandas\core\series.py in __getitem__(self, key)
    621         key = com._apply_if_callable(key, self)
    622         try:
--> 623             result = self.index.get_value(self, key)
    624 
    625             if not is_scalar(result):

c:\python36\lib\site-packages\pandas\core\indexes\base.py in get_value(self, series, key)
   2558         try:
   2559             return self._engine.get_value(s, k,
-> 2560                                           tz=getattr(series.dtype, 'tz', None))
   2561         except KeyError as e1:
   2562             if len(self) > 0 and self.inferred_type in ['integer', 'boolean']:

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_value()

pandas\_libs\index.pyx in pandas._libs.index.IndexEngine.get_loc()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

pandas\_libs\hashtable_class_helper.pxi in pandas._libs.hashtable.Int64HashTable.get_item()

KeyError: 0

但是,當我執行以下代碼(僅打印數據幀的標頭)時,不會遇到此類錯誤:

for file in os.listdir():
   df = pd.read_csv(file)
   df = df.fillna('NULL')
   if(len(df)>1):
       dfs = partDF(df , lim)
       for k in dfs.keys():
           aux = dfs[k]
           print('\t\t\t\tOriginal length : ' + str(len(aux)))
           print(aux.head(10))
           #insert2SQL(aux, table)
           del(aux)
   del(df, dfs)

我不知道發生了什么,如果有人可以幫助我,我會很高興。

PS。 我之所以沒有發布partDF()代碼,是因為我認為從這兩個代碼段中可以很清楚地看出這不是錯誤的原因。

PS2。 insert2SQL代碼:

def insert2SQL(tablilla, sqlTab):
    # connection data
    # servName = 'server'
    # userName = 'me'
    # psswd = 'pass'
    # cnxn = pyodbc.connect(driver='{SQL Server}', server=servName, UID=userName, PWD=psswd)
    # cursor = cnxn.cursor()

    rows = len(tablilla)
    fields = tablilla.columns
    vals = list()
    for field in tablilla.columns:
        if(type(tablilla[field][0]) == str):
            vals.append(True)
        else:
            vals.append(False)

    textFields = dict(zip(fields, vals))
    q = "INSERT INTO " + sqlTab + " VALUES ("

    for r in range(rows):
        for field in fields:
            if(str(tablilla.loc[r, field]) != 'NULL'):
                quot = "'" if textFields[field] else ""
            else:
                quot = ""
            q += quot + str(tablilla.loc[r, field]) + quot + ", "
        q = q[0:len(q)-2] + '),('  
    q = q[0:len(q)-2]

    print(q)
    print('\n')
    # cursor.execute(q)
    # cursor.commit()
    # cnxn.close()

編輯:

在您發表我的評論之后,我嘗試查看您的評論,發現我的錯誤是因為我總是嘗試比較每個數據框的第一行,卻忘記了在拆分大數據框后,大熊貓保留了索引行。 解決方案是將df.reset_index()應用於我發送到我的insert2SQL()函數的每個數據幀。

非常感謝!

PS。 只要您的評論對我有用,有什么方法可以投票贊成? 如何解決這個問題?

表是否在某處初始化? 您需要初始化它。

更新:在函數插入中檢查每次循環迭代時是否實際存在以下內容? -tablilla [field] [0]-textFields [field]-tablilla.loc [r,field]

我建議您逐一注釋掉每個for循環,看看是什么部分導致了錯誤。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM