我的文件包含Company、RecordID、Sale等列。当我在将文件加载到pandas dataframe后首次尝试查找其数据类型时,它列出了少数列的float/int。所以我把它们改成字符串如下;

data = pd.read_csv(filepath)
    print(data.dtypes)

Company Code          object
SiteCode               int64
Product Name          object
RECORD ID             int64
Tank ID                int64
Date                   int64
Sale Volume          float64
Deliveries Volume      int64
Dip Volume           float64

然后在将输出写入文件之前,将它们的类型更改为string;
>   data['RECORD ID'] = data['RECORD ID'].astype(str)
>      data['Tank ID'] = data['Tank ID'].astype(str)

我得到了;
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 107, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 131, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1607, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1614, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 'RECORD ID'

如果我注释recordid并让Tankid进行转换,那么对于Tankid我会得到相同的密钥错误,为什么?
这是csv示例;SIRA RECORD IDTANK ID列给出了问题
 Company Code,SiteCode,Product Name,SIRA RECORD ID,Tank ID,Date,Sale Volume,Deliveries Volume,Dip Volume
    XXX,20995,27PMAXDSL,3535352,4,20191004,4383.49,12902,16000
    XXX,20995,02ULP,3535351,3,20191004,8221.573,15996,9987.32
    XXX,20995,02ULP,3535350,2,20191004,7303.1,8201,11200

最佳答案

作为测试,不要手动输入列名,请尝试以下操作:

for col in data.columns:
    data[col] = data[col].astype(str)

这也适用于整个数据帧
data = data.astype('str')

08-24 15:27