Pythonic way to associate list of dataframes to list of strings

后端 未结 3 1793
花落未央
花落未央 2021-01-29 09:07

In encountered this problem when converting a json object to a csv:

I now have two lists:

list_A is a list of strings. Each string is a name of df.



        
相关标签:
3条回答
  • 2021-01-29 09:29

    You can associate them with a dict:

    df_dict = dict(zip(list_A, list_B))
    
    df_dict['df1'].head() ## Returns the first 10 rows of list_B[0]
    
    0 讨论(0)
  • 2021-01-29 09:34

    If you want three variables, the best way to do it is to assign them like this:

    df1, df2, df3 = list_B
    

    This will unpack the list giving values to each variable.

    For too many variables use:

    {'df{}'.format(i): df for i, df in enumerate(list_B, 1)}
    
    0 讨论(0)
  • 2021-01-29 09:44

    Either use a dictionary:

    dfs = dict(zip(list_A, list_B))

    then access individual dataframes with dfs['df1']:

    list_a = ['a', 'b', 'c']
    list_b = [1, 2, 3]
    d = dict(zip(list_a, list_b))
    print(d['a'])
    # 1
    

    or hack locals:

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

    Then you can access individual dataframes directly, df1, df2 etc:

    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
    
    0 讨论(0)
提交回复
热议问题