Home > other >  Loop Over every Nth item in Dictionary
Loop Over every Nth item in Dictionary

Time:10-05

can anyone advise how to loop over every Nth item in a dictionary? Essentially I have a dictionary of dataframes and I want to be able to create a new dictionary based on every 3rd dataframe item (including the first) based on index positioning of the original. Once I have this I would like to concatenate the dataframes together.

So for example if I have 12 dataframes , I would like the new dataframe to contain the first,fourth,seventh,tenth etc..

Thanks in advance!

CodePudding user response:

What you ask it a bit strange. Anyway, you have two main options.

  • convert your dictionary values to list and slice that:
out = pd.concat(list(dfs.values())[::3])

output:

   a  b  c
0  x  x  x
0  x  x  x
0  x  x  x
0  x  x  x
  • slice your dictionary keys and generate a subdictionary:
out = pd.concat({k: dfs[k] for k in list(dfs)[::3]})

output:

        a  b  c
df1  0  x  x  x
df4  0  x  x  x
df7  0  x  x  x
df10 0  x  x  x

Used input:

dfs = {f'df{i 1}': pd.DataFrame([['x']*3], columns=['a', 'b', 'c']) for i in range(12)}

CodePudding user response:

if the dict is required, you may use tuple of dict keys:

custom_dict = {
    'first': 1,
    'second': 2,
    'third': 3,
    'fourth': 4,
    'fifth': 5,
    'sixth': 6,
    'seventh': 7,
    'eighth': 8,
    'nineth': 9,
    'tenth': 10,
    'eleventh': 11,
    'twelveth': 12,
}
for key in tuple(custom_dict)[::3]:
    print(custom_dict[key])

then, you may call pandas.concat:

df = pd.concat(
    [
        custom_dict[key]
        for key in tuple(custom_dict)[::3]
    ],
    # =========================================================================
    # axis=0 # To Append One DataFrame to Another Vertically
    # =========================================================================
    axis=1 # To Append One DataFrame to Another Horisontally
)

assuming custom_dict[key] returns pandas.DataFrame, not int as in my code above.

  • Related