对于pandas dataframe中的无数据,我有两个结果不同的查询。
第一个查询:
with self.connection as conn:
query = f"""SELECT current_client_name, client_phone_number, profile, effective_date, effective_time,
client_details.telegram_id, telegram_reference
FROM `clients` JOIN `client_details`
ON clients.telegram_id=client_details.telegram_id
WHERE `status` = \'{status}\' order by effective_date"""
df_result = pd.read_sql_query(query, conn)
return df_result在没有找到任何记录的结果中,我看到了空的dataframe:
Empty DataFrame
Columns: [current_client_name, client_phone_number, profile, effective_date, effective_time, telegram_id, telegram_reference]
Index: []并且可以捕获具有下一个条件的空数据帧:
if df.empty is True:第二个查询
with self.connection as conn:
query = f"SELECT MAX(effective_date), effective_time FROM `client_details` WHERE `telegram_id` = {telegram_id} " \
f"and (`status` = \'WAIT\' or `status`= \'APPROVED\')"
df_result = pd.read_sql_query(query, conn)
return df_result由于某些原因,此查询返回的不是空的dataframe,而是列中没有数据的dataframe
df MAX(effective_date) effective_time
0 None None由于某些原因返回的数据帧不为空,因此无法使用下一个代码处理此结果!
if df.empty is True:有人知道为什么会发生这种情况吗:为什么在某些情况下返回空的dataframe,为什么在列中返回没有类型的dataframe?如何避免或处理这种情况?
谢谢
发布于 2021-03-31 19:29:23
在第一种情况下,您的查询不返回任何结果,因此您的df中没有条目。
在第二种情况下,您的查询返回一个结果,但是这些字段在您的SQL数据库中为空,因此您有一个非空的DataFrame,其中不包含任何值。
如果您只想要包含所有非空值的行(例如,示例中的两列都必须为非空值),或者如果某些空值为ok (例如,其中一列为Null,而另一列为非null ),则可以删除包含这些None值的行:
要删除包含任何None值的行,请执行以下操作:
df = df.dropna(how = 'any')要删除仅包含无值的行,请执行以下操作:
df = df.dropna(how = 'all')则check if df.empty应为True。
https://stackoverflow.com/questions/66886825
复制相似问题