使用pandas批量为多个DataFrame设置指定起止日期区间的方法
解决方案
你可以把所有需要处理的DataFrame放入一个列表中,通过遍历列表完成批量筛选,两种常用实现方式如下:
方式1:生成筛选后的新DataFrame列表(推荐,不修改原数据)
import pandas as pd # 先定义起止日期 start = pd.to_datetime('2021-01-02') end = pd.to_datetime('2021-01-04') # 把所有要处理的df放入列表 df_list = [df1, df2] # 批量筛选,生成新的结果列表 filtered_df_list = [df.loc[(df['Dates'] >= start) & (df['Dates'] <= end)] for df in df_list]
筛选后可通过下标访问结果:
filtered_df_list[0]对应筛选后的df1filtered_df_list[1]对应筛选后的df2
方式2:保留原变量名可结合字典使用
如果你希望筛选后仍然可以通过原变量名访问结果,可用字典存储所有DataFrame:
df_dict = {'df1': df1, 'df2': df2} # 批量筛选后覆盖原字典值 for name, df in df_dict.items(): df_dict[name] = df.loc[(df['Dates'] >= start) & (df['Dates'] <= end)]
访问方式:df_dict['df1']、df_dict['df2']
优化技巧
如果你的Dates列设置为索引,还可以用更简洁的写法:
# 写法1:用between简化条件判断 df.loc[df['Dates'].between(start, end)] # 写法2:日期作为索引后直接切片 df = df.set_index('Dates') filtered_df = df[start:end]
内容的提问来源于stack exchange,提问作者fjurt
相关产品推荐
相关产品推荐

