2017-06-12 77 views
0

这是一个非常奇怪的错误,我得到KeyError当做熊猫DataFrame groupby没有明显的原因。来自熊猫数据框组Keybyror由

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的,并且是从SQL Server SSMS输出的。这是非常重要的,因为我打开,复制&使用Notepad ++保存了完全的内容,并且新保存的文件不会有这样的问题。

使用file test.csv Linux下显示:

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 

任何想法如何解决呢?谢谢。

+0

你可以试试'df.columns = DF。 columns.map(str.strip)' – piRSquared

+0

@piRSquared,谢谢,但没有任何不同。 OP已更新。 – xpt

回答

1

在Windows Line terminators从其他操作系统不同 - 在ASCII编码,在类Unix操作系统中的换行符是LF,在Windows它的CRLF。为了保持系统之间的兼容性,请使用Git allows the option来保存文件,以CRLF行结束于Windows,LF保存在其他操作系统中。这是导致你的问题 - 当pandas.read_csv运行你的文件与SQL Server保存,它有CRLF行结束和pandas将其解释为在每行的末尾有一个额外的CR字符。

幸运的是,read_csv函数包含一个参数lineterminator,其中you can set to "\r",CR字符可让您的行正确读取。

+0

不幸的是,使用'lineterminator ='\ r''将不适用于我,因为Ids将被读作'\ nT5119'。我也试过'lineterminator ='\ r \ n',但会得到错误**'ValueError:只支持长度为1的行结束符** – xpt

1

到底了 - 它实际上是基于Windows的csv文件的根本原因。

证明:

  1. 我打开,复制&节省使用记事本++完全相同的内容,也不会有这样的问题与新保存的文件。
  2. 如果我在Linux下使用dos2unix进行转换,那么尝试使用上述相同的代码即可。 groupby不会再抛出异常。

https://github.com/pandas-dev/pandas/issues/16690

建档的错误并解决它,如果大熊猫是比0.19更早,使用encoding='utf-8-sig'pd.read_csv

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