Python 如何使用pandas转换Excel文件中的所有列

Python 如何使用pandas转换Excel文件中的所有列,python,pandas,converters,Python,Pandas,Converters,我想将excel文件中的所有列(59列)转换为数据框,并指定类型。 有些列是字符串,有些是日期,有些是int等等。 我知道我可以在read_excel方法中使用转换器。 但是我有很多列,我不想要write converter={'column1':type1,'column2':type2,'column59':type59} 我的代码是: import numpy as np import pandas as pd import recordlinkage import xrld fileN

我想将excel文件中的所有列(59列)转换为数据框,并指定类型。 有些列是字符串,有些是日期,有些是int等等。 我知道我可以在read_excel方法中使用转换器。 但是我有很多列,我不想要write converter={'column1':type1,'column2':type2,'column59':type59}

我的代码是:

import numpy as np
import pandas as pd
import recordlinkage
import xrld

fileName = 'C:/Users/Tito/Desktop/banco ZIKA4.xlsx'
strcols = [0, 5, 31, 36, 37, 38, 39, 40, 41, 45]
datecols = [3, 4, 29, 30, 32, 48, 50, 51, 52, 53, 54, 55]
intcols = [33, 43, 59]
booleancols = [6, ..., 28]
df = pd.read_excel(fileName, sheet_name=0, true_values=['s'], false_values=['n'], converters={strcols: str, intcols: np.int, booleancols: np.bool, datecols: pd.to_datetime})
print(df.iat[1, 31], df.iat[1, 32], df.iat[1, 33])

Iiuc您的代码不起作用,因为
转换器
kwarg不允许将多个列的列表作为函数的键

您可以做的是创建dict而不是列表,并将连接的dict提供给
转换器

strcols = {c: str for c in [0, 5, 31, 36, 37, 38, 39, 40, 41, 45]}
datecols = {c: pd.to_datetime for c in [3, 4, 29, 30, 32, 48, 50, 51, 52, 53, 54, 55]}
intcols = {c: np.int for c in [33, 43, 59]}
booleancols = {c: np.bool for c in range(6, 29)}
conv_fcts = {**strcols, **datecols, **intcols, **booleancols}

df = pd.read_excel(fileName, converters=conv_fcts, sheet_name=0, true_values=['s'], false_values=['n'])