【发布时间】:2018-02-17 12:18:46
【问题描述】:
我有一个用例,我需要创建一个带有年份和月份的 python 字典,然后将所有数据帧连接到单个数据帧。我已经完成了如下实现:
dict_year_month = {}
temp_dict_1={}
temp_dict_2={}
for ym in [201104,201105 ... 201706]:
key_name = 'df_'+str(ym)+'A'
temp_dict_1[key_name]=df[(df['col1']<=ym) & (df['col2']>ym)
& (df['col3']==1)]
temp_dict_2[key_name]=df[(df['col1']<=ym) & (df['col2']==0)
& (df['col3']==1)]
if not temp_dict_1[key_name].empty:
dict_year_month [key_name] =temp_dict_1[key_name]
dict_year_month [key_name].loc[:, 'new_col'] = ym
elif not temp_dict_2[key_name].empty:
dict_year_month [key_name] =temp_dict_2[key_name]
dict_year_month [key_name].loc[:, 'new_col'] = ym
dict_year_month [key_name]=dict_year_month [key_name].sort_values('col4')
dict_year_month [key_name]=dict_year_month [key_name].drop_duplicates('col5')
.. do some other processing
create individual dataframes as df_201104A .. and so on ..
dict_year_month
#concatenate all the above individual dataframe into single dataframe:
df1 = pd.concat([
dict_year_month['df_201104A'],dict_year_month['df_201105A'],
... so on till dict_year_month['df_201706A'])
现在的挑战是我必须在每个季度重新运行一组代码,所以每次我必须使用新的 yearmonths dict 键和 pd.concat 更新此脚本时,还需要使用新年月份的详细信息进行更新。我正在寻找其他一些解决方案,通过它我可以读取键并从属性文件或配置文件中创建连接的数据框列表?
【问题讨论】:
标签: python python-3.x pandas dictionary dataframe