如何使用 pandas 转换 Excel 文件中的所有列
How can I convert all columns from my Excel file using pandas
我想将我的 excel 文件中的所有列(59 列)转换为数据框,并指定类型。
有些列是字符串,有些是日期,有些是 int 等等。
我知道我可以在 read_excel 方法中使用转换器。
但我有很多专栏,我不想写 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 你的代码不起作用,因为 converters
kwarg 不允许将多个列的列表作为函数的键。
您可以做的是创建字典而不是列表,并将串联的字典提供给 converters
:
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'])
我想将我的 excel 文件中的所有列(59 列)转换为数据框,并指定类型。 有些列是字符串,有些是日期,有些是 int 等等。 我知道我可以在 read_excel 方法中使用转换器。 但我有很多专栏,我不想写 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 你的代码不起作用,因为 converters
kwarg 不允许将多个列的列表作为函数的键。
您可以做的是创建字典而不是列表,并将串联的字典提供给 converters
:
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'])