从嵌套字典中根据条件提取数据框。

huangapple go评论56阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2023年3月7日 01:57:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75654231.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定