创建数据框的嵌套字典时,如何根据数据框的列表名称命名字典?
给出以下内容:
import pandas as pd
cars = {'Brand': ['Honda Civic','Toyota Corolla'],
'Price': [22000,25000]
}
df_cars = pd.DataFrame(cars, columns = ['Brand','Price'])
trucks = {'Brand': ['GMC Sierra','Ford F-150'],
'Price': [50000,48000]
}
df_trucks = pd.DataFrame(trucks, columns = ['Brand','Price'])
list_of_dfs = [df_cars, df_trucks]
# Not exactly sure how this code should be:
dict_of_dfs = {}
for df in list_of_dfs:
dict_of_dfs[name_of_df] = {}
dict_of_dfs[name_of_df]['results'] = df
我正在尝试使用for循环来产生以下结果:
dict_of_dfs['df_cars'] = {}
dict_of_dfs['df_cars']['results'] = df_cars
dict_of_dfs['df_trucks'] = {}
dict_of_dfs['df_trucks']['results'] = df_trucks
应会产生所需的输出,例如:
{
'df_cars': {
'results':
Brand Price
0 Honda Civic 22000
1 Toyota Corolla 25000},
'df_trucks': {
'results':
Brand Price
0 GMC Sierra 50000
1 Ford F-150 48000}
}
我已经阅读了多个线程,使用了模块varname
,并尝试使用enumerate()
,但是没有成功。
谢谢!