我在python 3中有一个带有mysql.connector的SQL查询。我正在将fetchall的结果转换为pandas数据帧。
mycursor.execute(sql_query)
m_table = pd.DataFrame(mycursor.fetchall())
m_table.columns = [i[0] for i in mycursor.description]
获取dtypes给了我:
Out[185]:
sales_forecast_id int64
year int64
products_id int64
test_string object
reconduit int64
target_week_1 int64
target_week_2 int64
year_n_1 int64
two_week_before object
first_week_before object
second_week_before object
two_week_before_n_1 object
first_week_before_n_1 object
second_week_before_n_1 object
CIBLE_n_1 int64
dtype: object
Testrongtring是我为测试添加的一个伪列,它在所有行中都包含"test"
。
现在,这个test_string
列和从two_week_before
到second_week_before_n_1
的另一列显示为dtype对象。所以test_string
是数据库中的一个字符串,其他的都是十进制的。但是对于dtype对象,我无法与另一个浮点类型的列执行乘法运算。
现在,我实际上有数百列这样的列,当它是decimal/int时,我想将所有的dtype对象转换为float,而当它是字符串时,转换为string。
我怎么能自动做到呢。如何知道对象是字符串还是十进制?
谢谢。
这是一种将此转换应用于所有列的简单方法,以防您确信需要将它们所有转换为浮点,但不能转换的列除外(因为它们包含字符串(:
import numpy as np
import pandas as pd
data = {'a':[1,2,3,4],'b':['a','b','aa','abc'],'c':[100,13,14,'xD']}
df = pd.DataFrame(data)
df['a'] = df['a'].astype('object')
print(df.dtypes)
输出(其中列a
的类型为object
,而应为int
或float
(:
a object
b object
c object
dtype: object
应用以下内容:
for i in list(data):
try:
df[i] = df[i].astype('float')
except ValueError:
df[i] = df[i].astype('object')
print(df.dtypes)
输出:
a float64
b object
c object
dtype: object