簡體   English   中英

來自Pandas DataFrame groupby的KeyError

[英]KeyError from pandas DataFrame groupby

這是一個很奇怪的錯誤,我得到了KeyError做熊貓數據幀時groupby沒有明顯的理由。

df = pd.read_csv('test.csv')
df.tail(5)

df.info()
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 165 entries, 0 to 164
Data columns (total 3 columns):
Id     165 non-null object
Time    165 non-null object
Val     165 non-null float64
dtypes: float64(1), object(2)
memory usage: 3.9+ KB

df.columns
Index([u'Id', u'Time', u'Val'], dtype='object')

df.groupby(['Id'])
KeyErrorTraceback (most recent call last)
<ipython-input-24-bba5c2dc5f75> in <module>()
----> 1 df.groupby(['Id'])

/usr/local/lib/python2.7/dist-packages/pandas/core/generic.pyc in groupby(self, by, axis, level, as_index, sort, group_keys, squeeze, **kwargs)
   3776         return groupby(self, by=by, axis=axis, level=level, as_index=as_index,
   3777                        sort=sort, group_keys=group_keys, squeeze=squeeze,
-> 3778                        **kwargs)
...
/usr/local/lib/python2.7/dist-packages/pandas/core/internals.pyc in get(self, item, fastpath)
   3288 
   3289             if not isnull(item):
-> 3290                 loc = self.items.get_loc(item)
   3291             else:
   3292                 indexer = np.arange(len(self.items))[isnull(self.items)]

/usr/local/lib/python2.7/dist-packages/pandas/indexes/base.pyc in get_loc(self, key, method, tolerance)
   1945                 return self._engine.get_loc(key)
   1946             except KeyError:
-> 1947                 return self._engine.get_loc(self._maybe_cast_indexer(key))
   1948 
   1949         indexer = self.get_indexer([key], method=method, tolerance=tolerance)

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4154)()

pandas/index.pyx in pandas.index.IndexEngine.get_loc (pandas/index.c:4018)()

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12368)()

pandas/hashtable.pyx in pandas.hashtable.PyObjectHashTable.get_item (pandas/hashtable.c:12322)()

KeyError: 'Id'

請注意,按建議使用df.columns = df.columns.map(str.strip)並沒有什么不同-我仍然從df.columns和錯誤中獲得完全相同的輸出,如上所述:

df.columns = df.columns.map(str.strip)
df.columns
Out[38]:
Index([u'Id', u'Time', u'Val'], dtype='object')

如果可以在任何地方發布此“ test.csv”,我可以這樣做,因為我幾乎可以確定問題出在文件格式上,“ test.csv”基於Windows,並且是從Windows輸出的SQL Server SSMS。 這一點非常重要,因為我使用Notepad ++打開,復制並保存了確切的內容,新保存的文件不會出現此類問題。

在Linux下使用file test.csv顯示:

test.csv: UTF-8 Unicode (with BOM) text, with CRLF line terminators

以下是文件中的前幾個字節:

0000000 ef bb bf 49 64 2c 54 69 - 6d 65 2c 56 61 6c 0d 0a  Id,Time,Val..
0000020 54 35 31 31 35 2c 30 30 - 3a 30 30 3a 30 30 2c 32  T5115,00:00:00,2
0000040 30 2e 38 31 39 0d 0a 54 - 35 31 31 35 2c 30 30 3a  0.819..T5115,00:
0000060 30 30 3a 30 33 2c 31 36 - 2e 39 32 36 0d 0a 54 35  00:03,16.926..T5
0000100 31 31 35 2c 30 30 3a 30 - 30 3a 30 38 2c 31 31 2e  115,00:00:08,11.
0000120 33 34 33 0d 0a 54 35 31 - 31 35 2c 30 30 3a 30 30  343..T5115,00:00
0000140 3a 31 37 2c 36 2e 39 37 - 35 0d 0a 54 35 31 31 35  :17,6.975..T5115
0000160 2c 30 30 3a 30 30 3a 32 - 39 2c 31 33 2e 35 35 33  ,00:00:29,13.553
0000200 0d 0a 54 35 31 31 35 2c - 30 30 3a 30 30 3a 33 35  ..T5115,00:00:35

知道如何解決嗎? 謝謝。

Windows中的行終止符與其他操作系統不同-在ASCII編碼中,類Unix操作系統中的換行符為LF ,在Windows中為CRLF 為了保持系統之間的兼容性, Git允許選擇CRLF行結尾的文件保存在Windows中,而在其他操作系統中以LF結尾。 這引起了您的問題-當pandas.read_csv在使用SQL Server保存的文件上運行時,它具有CRLF行結尾,而pandas則將其解釋為每行末尾都有一個額外的CR字符。

幸運的是, read_csv函數包含一個參數lineterminator可以將設置為 CR字符"\\r" ,以正確讀取行。

深入了解它-實際上是基於Windows的csv文件是根本原因。

證明:

  1. 我使用Notepad ++打開,復制並保存了確切的內容,新保存的文件不會出現此類問題。
  2. 如果我在Linux下使用dos2unix進行了轉換,然后嘗試上面的相同代碼,它將可以正常工作。 groupby將不再拋出異常。

https://github.com/pandas-dev/pandas/issues/16690提交了錯誤

解決的方法是,如果熊貓早於0.19,請在pd.read_csv使用encoding='utf-8-sig'

df = pd.read_csv('test.csv', encoding='utf-8-sig')

暫無
暫無

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

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