我使用 Windows PC 上的 jupyter 笔记本。我读了一个数据帧,我调用 tran 如下tran = pd.read_csv("https://raw.githubusercontent.com/m1ngle/TRCount/main/TRCountUS.csv")当我查看整个数据框的数据类型时,它效果很好tran.dtypesFIPS int64State objectYMTF int64MTFPer float64YFTM int64FTMPer float64YNB int64NBPer float64YTR int64YTRper float64NoTR int64NoTRPer float64DK int64DKPer float64DNAns int64DNAPer float64TotSurveyed int64StatePop int64TRPop int64dtype: object当我尝试调用或使用任何 float64 列时,我收到错误tran['MTFPer'].dtypeKeyError Traceback (most recent call last)~\anaconda3\lib\site-packages\pandas\core\indexes\base.py in get_loc(self, key, method, tolerance) 2645 try:-> 2646 return self._engine.get_loc(key) 2647 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: 'MTFPer'During handling of the above exception, another exception occurred:KeyError Traceback (most recent call last)<ipython-input-85-2bd9c012f223> in <module>----> 1 tran['MTFPer'].dtype~\anaconda3\lib\site-packages\pandas\core\frame.py in __getitem__(self, key) 2798 if self.columns.nlevels > 1: 2799 return self._getitem_multilevel(key)-> 2800 indexer = self.columns.get_loc(key) 2801 if is_integer(indexer): 2802 indexer = [indexer]当我使用任何 int64 数据类型时,不会发生此错误。tran['YMTF'].dtypedtype('int64')谁能帮我吗?
1 回答
潇湘沐
TA贡献1816条经验 获得超6个赞
在读取.csv
文件时,pandas 还会读取列中的空白。当我tran[' MTFPer '].dtype
代替 时tran['MTFPer'].dtype
,pandas 给了我正确的答案。
也许稍微清理一下数据本身,或者您可以像这样清理列名:
tran.columns = [c.strip() for c in tran.columns]
添加回答
举报
0/150
提交
取消