循环遍历数据框字典
Posted
技术标签:
【中文标题】循环遍历数据框字典【英文标题】:Loop through a dictionary of dataframes 【发布时间】:2019-08-18 16:58:32 【问题描述】:我有一组数据框,代表我已放入字典的需求场景。我需要遍历字典中的每个数据框以重新索引和重新采样等并返回到字典。当我遍历数据框列表时,以下代码可以完美运行,但我需要维护每个场景的身份,因此需要维护字典。
这是适用于数据框列表的代码:
demand_dfs_list = [low_demand_df, med_low_demand_df, bc_demand_df, med_high_demand_df, high_demand_df]
dates = pd.date_range(start='2020-10-01', end='2070-09-30', freq='D')
demand_dfs_datetime = []
for df in demand_dfs_list:
df.index = pd.to_datetime(df.index, format='%Y')
df = df.tshift(-92, 'D')
df = df.resample('D').ffill()
df = df.reindex(dates)
demand_dfs_datetime.append(df)
这是我尝试过的字典形式:
demand_scenarios = 'low': low_demand_df, 'medium_low': med_low_demand_df, 'medium': bc_demand_df, 'medium_high': med_high_demand_df, 'high': high_demand_df
dates = pd.date_range(start='2020-10-01', end='2070-09-30', freq='D')
demand_dict =
for df in demand_scenarios:
[df].index = pd.to_datetime([df].index, format='%Y')
[df] = [df].tshift(-92, 'D')
[df] = [df].resample('D').ffill()
[df] = [df].reindex(dates)
demand_dict[df] = df
跟进问题 我使用以下命令将上面的 demand_dict 字典传递到一个 xarray 中:
demand_xarray = xr.Dataset(demand_dict, coords = 'customers': customers, 'time': dates)
但是我的数据集如下所示:
<xarray.Dataset>
Dimensions: (customers: 28, dim_0: 18262, dim_1: 28, time: 18262)
Coordinates:
* dim_0 (dim_0) datetime64[ns] 2020-10-01 2020-10-02 ... 2070-09-30
* dim_1 (dim_1) object 'Customer_1' ... 'Customer_x'
* customers (customers) <U29 'Customer_1' ... 'Customer_x'
* time (time) datetime64[ns] 2020-10-01 2020-10-02 ... 2070-09-30
Data variables:
low (dim_0, dim_1) float64 0.52 0.528 3.704 ... 7.744 0.92 64.47
medium_low (dim_0, dim_1) float64 0.585 0.594 4.167 ... 8.712 1.035 72.53
medium (dim_0, dim_1) float64 0.65 0.66 4.63 12.6 ... 9.68 1.15 80.59
medium_high (dim_0, dim_1) float64 0.715 0.726 5.093 ... 10.65 1.265 88.65
high (dim_0, dim_1) float64 0.78 0.792 5.556 ... 11.62 1.38 96.71
当我尝试像这样使用 drop_dims 函数时:
demand_xarray = xr.Dataset(demand_dict, coords = 'customers': customers, 'time': dates).drop_dims(dim_0, dim_1)
我得到错误:
AttributeError: 'Dataset' object has no attribute 'drop_dims'
知道为什么会出现此错误吗?
【问题讨论】:
【参考方案1】:demand_scenarios = 'low': low_demand_df, 'medium_low': med_low_demand_df, 'medium': bc_demand_df, 'medium_high': med_high_demand_df, 'high': high_demand_df
dates = pd.date_range(start='2020-10-01', end='2070-09-30', freq='D')
demand_dict =
for key, df in demand_scenarios.items():
df.index = pd.to_datetime([df].index, format='%Y')
df = df.tshift(-92, 'D')
df = df.resample('D').ffill()
df = df.reindex(dates)
demand_dict[key] = df
items()
返回字典的键和值
【讨论】:
太棒了,谢谢。我的 to_datetime 行出现错误,但事实证明我在使用字典时实际上不需要将索引转换为日期时间......不确定我是否完全理解,但它正在工作!以上是关于循环遍历数据框字典的主要内容,如果未能解决你的问题,请参考以下文章