英文:
Pull Dataframes out of Nested Dictionary based on condition
问题
for key in df_dict.keys():
if '.' not in key: # if key name does not contain a period
locals()[key] = pd.DataFrame(df_dict[key]) # create a new dataframe with the key name
英文:
I have a dictionary of dataframes called df_dict.
df_dict.keys()
dict_keys(['df1.test', 'df2.test', 'df3.test','df1_test','df2_test','df3_test'])
Each key is a separate dataframe that has its own columns and data associated with it. How do I lift those dataframes that DO NOT have (".") in their title out of the dictionary so they are dataframes in their own right, not part of the dictionary?
I know I can do the following, but it's cumbersome and I may be adding to this list in the future.
df1_test= pd.DataFrame(df_dict['df1_test'])
df2_test= pd.DataFrame(df_dict['df2_test'])
df3_test= pd.DataFrame(df_dict['df3_test'])
I'd like something that loops through the dictionary and creates a new dataframe each time.
for key in df_dict.keys():
if !key.str.contains(pat = '.'): # how to negate? if key name does not contain a period
key = pd.DataFrame(df_dict[key]) #i want the dataframes to be the key names
End goal is to have 3 dataframes outputed - df1_test, df2_test, df3_test
答案1
得分: 1
如果我理解您的要求,您想从字典中创建DataFrame的名称。可以从字符串创建全局名称,并将其分配给对象:
for key, df in df_dict.items():
if '.' not in key:
globals()[key] = df
然后,选定的3个DataFrame将分配所需的名称,分别为df1_test、df2_test和df3_test,可以根据需要使用它们。
英文:
If I understand your requirement you want to create DF names from the Dictionary. It is possible to create global names from strings and assign these to objects:
for key,df in df_dict.items():
if '.' not in key:
globals()[(key)] = df
The 3 selected DFs will then have the required names assigned df1_test, df2_test, df3_test and these can be used as required.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论