为什么 Pandas 中的数据类型与 SQL 中的数据类型不同
Why the datatypes in Pandas are different from those in SQL
我是 SQLite 和 Python 的新手,并且在该主题中很受欢迎。
我导入一个 SQLite table
SQL Table Column Data Type 变成 Python
使用代码
conn = sqlite3.connect("C:\SQLite\aaa.sqlite")
df=pd.read_sql(sql="select * from C",con=conn,coerce_float=True)
当我检查 Python 中的数据类型时。
有些是对象
df.dtypes
WD float64
Manpower float64
2nd object
CTR object
2ndU float64
T1 object
T2 object
T3 object
T4 object
T5 object
你知道为什么 Python 将某些列从 float64 转换为 Object 吗?
Pandas 将 return 具有 dtype object
列的 DataFrame 如果该列至少包含一个不是浮点数的值。例如,一个字符串——即使是一个空字符串——也会强制整个列为对象数据类型:
import sqlite3
import numpy as np
import pandas as pd
filename = '/tmp/test.sqlite'
with sqlite3.connect(filename) as conn:
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS C')
cursor.execute('CREATE TABLE C (CTR float)')
sql = 'INSERT INTO C VALUES (?)'
args = [(x, ) for x in np.random.random(5)] + [('',)]
cursor.executemany(sql, args)
df = pd.read_sql(sql="SELECT * FROM C",
con=conn, coerce_float=True)
print(df)
# CTR
# 0 0.1205763
# 1 0.5859016
# 2 0.9511995
# 3 0.08459435
# 4 0.8094845
# 5
print(df.dtypes)
产量
CTR object
dtype: object
我是 SQLite 和 Python 的新手,并且在该主题中很受欢迎。
我导入一个 SQLite table SQL Table Column Data Type 变成 Python
使用代码
conn = sqlite3.connect("C:\SQLite\aaa.sqlite")
df=pd.read_sql(sql="select * from C",con=conn,coerce_float=True)
当我检查 Python 中的数据类型时。 有些是对象
df.dtypes
WD float64
Manpower float64
2nd object
CTR object
2ndU float64
T1 object
T2 object
T3 object
T4 object
T5 object
你知道为什么 Python 将某些列从 float64 转换为 Object 吗?
Pandas 将 return 具有 dtype object
列的 DataFrame 如果该列至少包含一个不是浮点数的值。例如,一个字符串——即使是一个空字符串——也会强制整个列为对象数据类型:
import sqlite3
import numpy as np
import pandas as pd
filename = '/tmp/test.sqlite'
with sqlite3.connect(filename) as conn:
cursor = conn.cursor()
cursor.execute('DROP TABLE IF EXISTS C')
cursor.execute('CREATE TABLE C (CTR float)')
sql = 'INSERT INTO C VALUES (?)'
args = [(x, ) for x in np.random.random(5)] + [('',)]
cursor.executemany(sql, args)
df = pd.read_sql(sql="SELECT * FROM C",
con=conn, coerce_float=True)
print(df)
# CTR
# 0 0.1205763
# 1 0.5859016
# 2 0.9511995
# 3 0.08459435
# 4 0.8094845
# 5
print(df.dtypes)
产量
CTR object
dtype: object