使用panda模块读取csv时出错

时间:2017-10-06 00:51:42

标签: python file pandas module keyerror

companyName = companyList[companyID-1]
data = pd.read_csv("C:\Feedback and Complaints_Sample Dataset.csv",sep=',')  # read file with panda module
desiredOutput = data["Co. Name" == companyName]
desiredOutput.to_csv("1.txt", sep = ",", index=False, header=False)
desiredOutput = data["Co. Name" == companyName]  # For desiredOutput, it'll be when co-name equals companyName

我在使用熊猫模块时收到了错误消息。 请指教。 以下是错误消息:

   desiredOutput = data["Co. Name" == companyName]
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1797, in __getitem__
    return self._getitem_column(key)
  File "C:\Python27\lib\site-packages\pandas\core\frame.py", line 1804, in _getitem_column
    return self._get_item_cache(key)
  File "C:\Python27\lib\site-packages\pandas\core\generic.py", line 1084, in _get_item_cache
    values = self._data.get(item)
  File "C:\Python27\lib\site-packages\pandas\core\internals.py", line 2851, in get
    loc = self.items.get_loc(item)
  File "C:\Python27\lib\site-packages\pandas\core\index.py", line 1572, in get_loc
    return self._engine.get_loc(_values_from_object(key))
  File "pandas\index.pyx", line 134, in pandas.index.IndexEngine.get_loc (pandas\index.c:3824)
  File "pandas\index.pyx", line 154, in pandas.index.IndexEngine.get_loc (pandas\index.c:3704)
  File "pandas\hashtable.pyx", line 686, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12280)
  File "pandas\hashtable.pyx", line 694, in pandas.hashtable.PyObjectHashTable.get_item (pandas\hashtable.c:12231)
KeyError: False

1 个答案:

答案 0 :(得分:0)

如果您的data DataFrame包含列,名称为"Co. Name",那么您可以使用以下代码段获取具有指定条件的所有行:

companyName = companyList[companyID-1]
data = pd.read_csv("C:\Feedback and Complaints_Sample Dataset.csv",sep=',')  # read file with pandas module
desiredOutput = data[data["Co. Name"] == companyName]