0

I have a pandas data frame that looks like this:

x      |     week
___________________
234    |     40
345    |     40             
123    |     41   
155    |     41
213    |     41       
...    |     ...             
1452   |     52

and I need to create several data frames that each contains only one week

one for week 40, one for week 41, etc.

I have tried this so far:

length = len(data.index)-1
firstweek=data['week'].iloc[0]
lastweek=data['week'].iloc[length]
df = {}
for i in range (firstweek,lastweek):
     df[i]= pd.DataFrame(data.query('week== i'))
Edu Galindo
  • 165
  • 1
  • 8

1 Answers1

1

You hard coded the variable i. Assuming you're using Python 3.6+, you can use an f string for string interpolation. If you're using Python 2 or an earlier version of 3, you can use the .format method.

Python 3.6 +

length = len(data.index)-1
firstweek=data['week'].iloc[0]
lastweek=data['week'].iloc[length]
df = {}
for i in range (firstweek,lastweek):
     df[i]= pd.DataFrame(data.query(f'week=={i}'))

Python 2 & 3

length = len(data.index)-1
firstweek=data['week'].iloc[0]
lastweek=data['week'].iloc[length]
df = {}
for i in range (firstweek,lastweek):
     df[i]= pd.DataFrame(data.query('week=={i}'.format(i=i)))

Further reading: https://www.programiz.com/python-programming/string-interpolation