pandas将excel读取为带空格值和字符串的字符串

2024-05-23 14:26:06 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一张excel表格,我需要在Tel#列中使用混合数据类型列来阅读。我在excel中将“电话”列设置为文本字段

样本数据

df = pandas.DataFrame.from_dict({'SFDC ID': ['001','002', '003'], 'Name': ['company1', 'company2', 'company3'], 'Tel#': [pandas.np.NaN, '123-456-789',12345678.0]})

所需输出

此表中的数据将进入SQL Server数据库,而Tel系列将进入nvarchar列。缺少的值应作为NULL输入,转换后的浮点数应作为其字符串表示形式输入,不带小数点。 示例SQL语句

INSERT INTO #table1 ([SFDC ID], [Name], [Tel#]) VALUES ('001', 'company1', NULL)
INSERT INTO #table1 ([SFDC ID], [Name], [Tel#]) VALUES ('002', 'company2', '123-456-789')
INSERT INTO #table1 ([SFDC ID], [Name], [Tel#]) VALUES ('001', 'company1', '12345678')

对于当前插入,由于excel工作表中缺少值,我的SQL以浮点表示形式插入值

df = pandas.read_excel(filename, dtypes=str, sheet_name='Flatfile')

df = df.mask(df.isna(), None)

我还尝试将其转换为“Int64”,因为它支持NaN/NULL值,但显然不适用于带破折号的Tel


Tags: 数据nameidpandasdfsqlsfdcexcel
1条回答
网友
1楼 · 发布于 2024-05-23 14:26:06

IIUC您需要用None填充缺少的值,并将所有其他值转换为字符串。在这种情况下,您可以将^{}None一起使用:

df.astype(str).mask(df.isna(), None)

例如:

df
#   SFDC ID      Name         Tel#
#0        1  company1          NaN
#1        2  company2  123-456-789
#2        3  company3     12345678

df.applymap(type)
#         SFDC ID           Name             Tel#
#0  <class 'int'>  <class 'str'>  <class 'float'>
#1  <class 'int'>  <class 'str'>    <class 'str'>
#2  <class 'int'>  <class 'str'>    <class 'int'>

df.astype(str).mask(df.isna(), None)
#  SFDC ID      Name         Tel#
#0       1  company1         None
#1       2  company2  123-456-789
#2       3  company3     12345678

df.astype(str).mask(df.isna(), None).applymap(type)
#         SFDC ID           Name                Tel#
#0  <class 'str'>  <class 'str'>  <class 'NoneType'>
#1  <class 'str'>  <class 'str'>       <class 'str'>
#2  <class 'str'>  <class 'str'>       <class 'str'>

相关问题 更多 >