升级Pandas后插入行触发FutureWarning,如何解决?
解决DataFrame插入全NA行触发的FutureWarning问题
我有一个包含名为“ds”的日期时间列的DataFrame,数据完整,想要在现有数据前插入一行,使用了以下代码:
start = df_p['ds'].iloc[0] - pd.Timedelta(1,"d") if start not in df_p.index: df_p.loc[start] = np.NaN
执行后触发了FutureWarning:
FutureWarning: The behavior of DataFrame concatenation with empty or all-NA entries is deprecated. In a future version, this will no longer exclude empty or all-NA columns when determining the result dtypes. To retain the old behavior, exclude the relevant entries before the concat operation.
问题原因
直接用df.loc[start] = np.NaN插入全NA行时,pandas内部会执行隐式的DataFrame合并操作,而全NA行的存在会触发 dtype 推断的 deprecation 提示——未来版本不再会自动排除全NA列来推断结果 dtype。
解决方法
方法1:显式构造单行DataFrame后合并(推荐)
先创建和原DataFrame列结构完全一致的单行数据,指定“ds”列的目标日期,其他列设为NaN,再和原DataFrame合并,明确控制列的 dtype,避免隐式合并带来的警告:
import pandas as pd import numpy as np # 获取要插入的前一天日期 start = df_p['ds'].iloc[0] - pd.Timedelta(1, "d") # 构造匹配原DataFrame列结构的单行数据 new_row = pd.DataFrame({col: [np.NaN] for col in df_p.columns}) new_row['ds'] = start # 给ds列赋值目标日期 # 合并新行与原DataFrame,ignore_index=True重置索引(不需要的话可以去掉) df_p = pd.concat([new_row, df_p], ignore_index=True)
方法2:保留原索引逻辑的写法
如果需要保留原索引(比如用日期作为索引),可以先创建匹配列 dtype 的空Series,再合并:
start = df_p['ds'].iloc[0] - pd.Timedelta(1, "d") if start not in df_p.index: # 创建和原DataFrame列结构、dtype一致的空Series new_row = pd.Series(index=df_p.columns, dtype=df_p.dtypes) new_row['ds'] = start # 转成DataFrame后和原数据合并 df_p = pd.concat([new_row.to_frame().T, df_p])
内容的提问来源于stack exchange,提问作者Tunneller
相关产品推荐
相关产品推荐

