将数据帧列表关联到字符串列表的 Pythonic 方法

Pythonic way to associate list of dataframes to list of strings

在将 json 对象转换为 csv 时遇到此问题:

我现在有两个列表:

list_A 是一个字符串列表。每个字符串都是df.

的名字
list_A = ['df1', 'df2', 'df3'] 

list_B 有 3 个 pandas.core.frame.DataFrame 个对象。

list_B[0] = [an entire df with columns, rows etc]

什么代码可以确保一个列表中的字符串与另一个列表中的数据帧之间的关联,例如 df1 = list_B[0] 然后 df2 = list_B[1] 等等?

谢谢

您可以将它们与 dict:

df_dict = dict(zip(list_A, list_B))

df_dict['df1'].head() ## Returns the first 10 rows of list_B[0]

要么使用字典:

dfs = dict(zip(list_A, list_B))

然后使用 dfs['df1']:

访问单个数据帧
list_a = ['a', 'b', 'c']
list_b = [1, 2, 3]
d = dict(zip(list_a, list_b))
print(d['a'])
# 1

或破解 locals:

for name, df in zip(list_A, list_B):
    locals()[name] = df

然后你可以直接访问单个数据帧,df1df2等:

list_a = ['a', 'b', 'c']
list_b = [1, 2, 3]
for key, value in zip(list_a, list_b):
    locals()[key] = value
print(a)
#  1

如果你想要三个变量,最好的方法是这样分配它们:

df1, df2, df3 = list_B

这将解压缩为每个变量赋值的列表。

对于太多变量使用:

{'df{}'.format(i): df for i, df in enumerate(list_B, 1)}