TypeError: unsupported operand type(s) for -: 'NoneType' and 'float'
时间: 2023-07-29 12:14:43 浏览: 97
这个错误通常是由于在计算过程中出现了None值,无法与float类型进行计算导致的。您可以在计算之前先判断一下值是否为None,如果是None则跳过计算。以下是修改后的代码示例:
```
import pandas as pd
import pymysql
# 连接数据库
conn = pymysql.connect(host='localhost', port=3306, user='root', password='123456', db='daily')
# 获取所有表格名称
cursor = conn.cursor()
cursor.execute("show tables;")
tables = [table[0] for table in cursor.fetchall()]
# 遍历所有表格
for table in tables:
# 查询net_mf_amount列的数据,按照trade_date降序排列
sql = "select trade_date, net_mf_amount from `{}` order by trade_date desc;".format(table)
df = pd.read_sql(sql, conn)
# 对查询结果进行计算,将结果保存在a和b列中
if 'a' not in df.columns:
df['a'] = pd.Series([None]*len(df))
df['b'] = pd.Series([None]*len(df))
for i in range(len(df)):
if i == 0:
df.at[i, 'a'] = None
df.at[i, 'b'] = None
else:
if pd.isna(df.at[i, 'a']) and pd.isna(df.at[i, 'b']):
if pd.isna(df.at[i-1, 'net_mf_amount']) or pd.isna(df.at[i, 'net_mf_amount']):
continue
df.at[i, 'a'] = df.at[i-1, 'net_mf_amount'] - df.at[i, 'net_mf_amount']
if pd.isna(df.at[i-1, 'a']):
continue
df.at[i, 'b'] = df.at[i-1, 'a'] - df.at[i, 'a']
# 保存a和b列的值
cursor.execute("alter table `{}` add column if not exists a varchar(50);".format(table))
cursor.execute("alter table `{}` add column if not exists b varchar(50);".format(table))
for i in range(len(df)):
if pd.isna(df.at[i, 'a']) or pd.isna(df.at[i, 'b']):
continue
sql = "update `{}` set a = '{}', b = '{}' where trade_date = '{}';".format(table, df.at[i, 'a'], df.at[i, 'b'], df.at[i, 'trade_date'])
cursor.execute(sql)
# 提交修改并关闭连接
conn.commit()
cursor.close()
conn.close()
```
在代码中,我们加入了判断语句,当出现None值时,直接跳过计算即可。
阅读全文