Home > other >  Selecting DataFrames in List based on hour
Selecting DataFrames in List based on hour

Time:11-18

I have a list with 24 DataFrames with hourly prices for two years inside, I want to specify a For Loop so each of these DataFrames only show the price for a single hour per day.

I have come this far:

for i in range(24):
    dfs[i] = dfs[i][dfs[i]['hour_0'] == 1]

So this takes each row in the list and keeps the row if the set hour (here 'hour_0') is equal to 1 (in my hourly dummy variables).

The obvious problem here is that these piece of code only extract the first hour of the day, I would like something like below, which extracts a new hour for every row:

for i in range(24):
    dfs[i] = dfs[i][dfs[i]['hour_i'] == 1]

But this doesn't work.

Thankful for all the help.

CodePudding user response:

you can try:

for i in range(24):
    dfs[i] = dfs[i][dfs[i]['hour_' str(i)] == 1]

or with f-string, which is a bit cleaner:

for i in range(24):
    dfs[i] = dfs[i][dfs[i][f'hour_{i}'] == 1]
  • Related