简体   繁体   English

Python 将字符串转换为 object

[英]Python convert string to object

I am using pandas/sql alchemy to write a table to an sql database.我正在使用 pandas/sql alchemy 将表写入 sql 数据库。

Here is some sample code below:下面是一些示例代码:

df.to_sql('table', connection, schema=None, dtype={
    'id': sa.types.VARCHAR(length=100),
    'value1': sa.types.Float(),
    'value2': sa.types.Float()})

I have a csv file where the data type for each column is defined, I would like to be able to read the csv file using pandas and then convert the table to a dictionary which would be passed to the to_sql() method.我有一个 csv 文件,其中定义了每列的数据类型,我希望能够使用 pandas 读取to_sql()文件,然后将表转换为传递给字典的方法。

If I were to do that directly, the data type, for example sa.types.VARCHAR(length=100) would appear as a string.如果我直接这样做,数据类型,例如sa.types.VARCHAR(length=100)将显示为字符串。 How can I convert this string so that it can be passed as an appropriate data type.如何转换此字符串,以便可以将其作为适当的数据类型传递。

To clarify if i read the data from a csv table, the dtype dictionary will look like this:为了澄清我是否从 csv 表中读取数据,dtype 字典将如下所示:

{'id': 'sa.types.VARCHAR(length=100)'}

instead of the current:而不是当前的:

{'id': sa.types.VARCHAR(length=100)}

This solution is hacky and I have to believe there's a better way if we had all of the information, but short of that, here goes.这个解决方案很老套,我必须相信,如果我们掌握了所有信息,会有更好的方法,但如果没有,那就去吧。

I would create a dictionary similar to:我会创建一个类似于以下内容的字典:

type_dict = {
   'VARCHAR' : sa.types.VARCHAR,
   'Float'   : sa.types.Float, 
   ... }

Then, break up that string to get the main info you're looking for (I'm sure there's a better regex way to do this, but it's past my bedtime):然后,分解该字符串以获得您正在寻找的主要信息(我确信有更好的正则表达式方法可以做到这一点,但它已经过了我的就寝时间):

dtype = string.split('(')[0].split('.')[-1]
var   = string.split('(')[1].split('=').split(')')[0]

Then:然后:

sql_dict = { 'id' : type_dict[dtype](var) }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM