【问题标题】:Pandas: how to convert a column with missing values to string?Pandas:如何将缺少值的列转换为字符串?
【发布时间】:2018-04-30 04:14:43
【问题描述】:

我需要使用 SQL Alchemy 将数据框从 pandas 导出到 Microsoft SQL Server。许多列是字符串,缺少值和一些非常长的整数,例如999999999999999999999999999999999。这些数字是某种外键,所以值本身没有任何意义,所以我可以将它们转换为字符串。

这会在尝试导出到 SQL 时导致 SQL Alchemy 中出现以下错误:

OverflowError: int too big to convert

我尝试使用 astype(str) 转换为字符串,但后来我遇到了一个问题,即标识为 nans 的缺失值被转换为字符串 'nan' - 所以 SQL 不会将它们视为空值,而是将其视为字符串'南'。

我找到的唯一解决方案是先转换为 str,然后将 'nan' 替换为 numpy.nan。有没有更好的方法?这很麻烦,相对较慢,并且尽可能地不符合Python语言:首先我将所有内容转换为字符串,转换将空值转换为字符串,因此我将它们转换为NaN,这可以是只浮动,我最终得到一个混合类型的列。

或者我只是不得不接受它并接受熊猫在处理缺失值方面很糟糕?

下面有一个例子:

import numpy as np, pandas as pd, time

from sqlalchemy import create_engine, MetaData, Table, select
import sqlalchemy as sqlalchemy

start=time.time()
ServerName = "DESKTOP-MRX\SQLEXPRESS"
Database = 'MYDATABASE'
params = '?driver=SQL+Server+Native+Client+11.0'
engine = create_engine('mssql+pyodbc://' + ServerName + '/'+ Database + params, encoding ='latin1' )
conn=engine.connect()

df=pd.DataFrame()
df['mixed']=np.arange(0,9)
df.iloc[0,0]='test'
df['numb']=3.0
df['text']='my string'
df.iloc[0,2]=np.nan
df.iloc[1,2]=999999999999999999999999999999999

df['text']=df['text'].astype(str).replace('nan',np.nan)

print(df)

df.to_sql('test_df_mixed_types', engine, schema='dbo', if_exists='replace')

【问题讨论】:

  • 指定dtype=object.astype(object)
  • 列已经是一个对象了。

标签: python sql sql-server pandas nan


【解决方案1】:

使用np.where肯定会比替换快一点,即

df['text'] = np.where(pd.isnull(df['text']),df['text'],df['text'].astype(str))

时间:

%%timeit
df['text'].astype(str).replace('nan',np.nan)
1000 loops, best of 3: 536 µs per loop

%%timeit
np.where(pd.isnull(df['text']),df['text'],df['text'].astype(str))
1000 loops, best of 3: 274 µs per loop

x = pd.concat([df['text']]*10000)
%%timeit
np.where(pd.isnull(x),x,x.astype(str))
10 loops, best of 3: 28.8 ms per loop

%%timeit
x.astype(str).replace('nan',np.nan)
10 loops, best of 3: 33.5 ms per loop

【讨论】:

  • np.where 的解决方案也能正确处理 Series 已经包含 str "nan" 的边缘情况。 replace 的解决方案错误地用 np.nan 替换了它,它应该只传递 str "nan"。
猜你喜欢
  • 1970-01-01
  • 2016-08-30
  • 2020-10-22
  • 1970-01-01
  • 2016-11-05
  • 2016-09-17
  • 2020-11-20
  • 2019-01-14
  • 2018-01-27
相关资源
最近更新 更多