1

I am running a loop to slice table based on value of a given dictionary. But I would like to create one table for each loop and save table using the key of the dictionary. In the following example, I would like put the 'key' in table name df_slice, such as df_slice_loc1, df_slice_loc2

import numpy as np
import pandas as pd

df = pd.DataFrame({'group': ['A', 'B', 'C', 'D', 'E']
                  ,'scoreA': np.random.randn(5)
                  ,'scoreB': np.random.randn(5)})


loc_d = {"loc1":2, "loc2":3}

for key, value in loc_d.items():
    df_slice = df.iloc[:value,]
Gavin
  • 1,411
  • 5
  • 18
  • 31
  • If I'm understanding your question correctly, can't you just use another dictionary to store the keys from `loc_d` and map them to their corresponding `df.iloc[value,]`s? – prithajnath Oct 13 '18 at 05:06

1 Answers1

0

Use a dictionary for a variable number of variables

For example, using a dictionary comprehension:

df_slice = {key: df.iloc[:value] for key, value in loc_d.items()}

print(df_slice)

{'loc1':   group    scoreA    scoreB
0     A  0.139625 -0.321823
1     B  2.137781  0.103702,

 'loc2':   group    scoreA    scoreB
0     A  0.139625 -0.321823
1     B  2.137781  0.103702
2     C -1.000334  0.680955}

Then access a slice via, for example, df_slice['loc2'].

Community
  • 1
  • 1
jpp
  • 159,742
  • 34
  • 281
  • 339