Home > Mobile >  How to loop dataframe by year in pandas
How to loop dataframe by year in pandas

Time:12-24

I want to loop dataframe by year. For example my df is 2006-7-1 to 2021 length and 8 columns(A-H columns), index is datatime.
In this time,
df['A']['2006'] like that,

date
2006-07-01 00:00:00    1
2006-07-01 00:05:00    2
2006-07-01 00:10:00    3
2006-07-01 00:15:00    4

But I don't know how to loop by year 2006-2021, because we cannot write df['A']['i'].
So, please rent me your knowledge.

CodePudding user response:

You can simply create a column in the dataframe and then loop through it as follows

df['year'] = pd.DatetimeIndex(df['date']).year

Else you can try splitting the string and then extracting the year.

CodePudding user response:

You can create a column for Year:

df['Year'] = pd.DataFrame([i.year for i in df['Date']])

Then filter your dataframe using that column:

df['A'][df['Year'] == 2007]

This will give you all rows with year equals to 2007.

  • Related