Pandas 使用正确的数据类型读取excel并转换为CSV

Pandas 使用正确的数据类型读取excel并转换为CSV,pandas,numpy,types,integer,number-formatting,Pandas,Numpy,Types,Integer,Number Formatting,我是Python初学者。我有多个XLSX输入文件,我想读取Pandas数据帧中的XLSX,检查我感兴趣的字段是否具有正确的数据类型,然后转换CSV中的数据帧 实际上,我正在使用以下脚本: # import needed modules import pandas as pd import numpy as np import os # Select the input folder GMR_folder = r'C:\Users\Me\Desktop\MyFolder' # Read al

我是Python初学者。我有多个XLSX输入文件,我想读取Pandas数据帧中的XLSX,检查我感兴趣的字段是否具有正确的数据类型,然后转换CSV中的数据帧

实际上,我正在使用以下脚本:

# import needed modules
import pandas as pd
import numpy as np
import os

# Select the input folder 
GMR_folder = r'C:\Users\Me\Desktop\MyFolder'

# Read all the files within the folder 
files = os.listdir(GMR_folder)

# Read xlsx files within the folder 
files_xls = [f for f in files if f[-4:] == 'xlsx']

for file in files_xls:
    last_path = file
    member = (file[:-5])
    file_path = GMR_folder + "\\" + last_path
    # print(file_path)
    
    # Read the excel using specified datatype for the specified column 
    dataExcel = pd.read_excel(file_path, 
                         skiprows=range(0,3)

                        # define the datatype for each column we're intersted in 
                         dtype={'Col1':np.str,
                                'Col2':np.str,
                                'Col3':np.str,
                                'Col4':np.str,
                                'Col5':np.str,
                                'GPS Latitude (DD format) *': np.float32, 
                                'GPS Longitude (DD format) *': np.float32,
                                'GPS Latitude (Degrés décimaux) *':np.float32,
                                'GPS Longitude (Degrés décimaux) *':np.float32,
                                "Col10":np.int64,
                                "Col11":np.float64, 
                                "Col12":np.float64, 
                                "Col13":np.int64,
                                "Col14":np.float64,
                                "Col15":np.float64
                               })
                         
    
    # Insert the member ID in Col1
    dataExcel["Col1"] = member
    
    # Export the dataframe into a csv using the right encoding, useful to avoid strange char
    dataExcel.to_csv(member+'.csv',
                     encoding="utf-8-sig")

    print(member + ' csv created')

print( 'all csv created')
实际上,该脚本对于某些XLSX非常有效,但对于其他XLSX,我有以下错误:

Unable to convert column Col13 to type <class 'numpy.int64'>
无法将列Col13转换为类型
其他需要转换为float32的列也会发生这种情况


如何修复此错误?如果行中的NA值不能转换为正确的数据类型,那就太好了。我该怎么做呢?

查看有关Pandas新类型与Numpy类型的文档。
您需要将它们指定为“Int64”(大写I表示新的可空类型)

对于可空整数列,请尝试
pd.Int64