我是Python的新手,无法将CSV文件读取到pandas数据框中,如下所示。当我尝试引用第一列(“发票ID”)时出现KeyError。当我运行df.columns时显示。但是,当我运行df ['Invoice ID']时,出现KeyError,而当我在df.columns中运行'Invoice ID'时,它返回false。如何解决此问题,以便可以在不返回KeyError的情况下提取第一列?
SEC_df = pd.read_csv(SEC_file, header=1)
SEC_df.columns
Index(['Invoice ID ', 'Invoice Number ', 'Contact.Contact ID ',
'Contact.Name ', 'Date ', 'Due Date ', 'Branding Theme ID ', 'Status ',
'Line Amount Types ', 'Sub Total ', 'Total Tax ', 'Total ',
'Updated Date UTC ', 'Currency Code ', 'Fully Paid On Date ', 'Type ',
'Amount Paid ', 'Amount Due ', 'Amount Credited ', 'Sent To Contact ',
'Currency Rate ', 'Has Attachments ', 'Line Items.Line Item ID ',
'Line Items.Description ', 'Line Items.Unit Amount ',
'Line Items.Tax Type ', 'Line Items.Tax Amount ',
'Line Items.Line Amount ', 'Line Items.Account Code ',
'Line Items.Item Code ', 'Line Items.Quantity '],
dtype='object')
'Invoice ID ' in SEC_df.columns
False
SEC_df['Invoice ID ']
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2656 try:
-> 2657 return self._engine.get_loc(key)
2658 except KeyError:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'Invoice ID '
During handling of the above exception, another exception occurred:
KeyError Traceback (most recent call last)
<ipython-input-48-3e9c7cc16ac6> in <module>
----> 1 SEC_df['Invoice ID ']
~\Anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key)
2925 if self.columns.nlevels > 1:
2926 return self._getitem_multilevel(key)
-> 2927 indexer = self.columns.get_loc(key)
2928 if is_integer(indexer):
2929 indexer = [indexer]
~\Anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance)
2657 return self._engine.get_loc(key)
2658 except KeyError:
-> 2659 return self._engine.get_loc(self._maybe_cast_indexer(key))
2660 indexer = self.get_indexer([key], method=method, tolerance=tolerance)
2661 if indexer.ndim > 1 or indexer.size > 1:
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/index.pyx in pandas._libs.index.IndexEngine.get_loc()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
pandas/_libs/hashtable_class_helper.pxi in pandas._libs.hashtable.PyObjectHashTable.get_item()
KeyError: 'Invoice ID '