繁体   English   中英

将数据框列表与字符串列表相关联的 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

或 hack 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)}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM