📜  for loop pandas range - Python (1)

📅  最后修改于: 2023-12-03 15:15:10.069000             🧑  作者: Mango

For Loop with Pandas Range - Python

In Python, we can use a for loop with range to iterate over a sequence of numbers ranging from a specified start value up to (but not including) a specified end value. We can also use the pandas library to create a range of dates or times. In this guide, we will cover how to use a for loop with pandas range.

Prerequisites

To follow along with this guide, you should have:

  • Basic knowledge of Python programming language
  • Installed the pandas library
Using for loop with pandas date_range

The pandas library provides the date_range() function to generate a range of dates or times. The date_range() function takes several arguments, including:

  • start: Start date or time.
  • end: End date or time.
  • periods: Number of periods to generate.
  • freq: Frequency of dates or times to generate.

Here is an example of how to use date_range() with a for loop:

import pandas as pd

start_date = '2021-01-01'
end_date = '2021-01-05'

dates = pd.date_range(start=start_date, end=end_date)

for date in dates:
    print(date)

Output:

2021-01-01 00:00:00
2021-01-02 00:00:00
2021-01-03 00:00:00
2021-01-04 00:00:00
2021-01-05 00:00:00

In the above example, we first imported the pandas library and defined the start_date and end_date. We then used the date_range() function to create a range of dates between the start_date and end_date. Finally, we used a for loop to iterate over the dates and print each date.

Using for loop with pandas period_range

The pandas library also provides the period_range() function to generate a range of periods. The period_range() function takes several arguments, including:

  • start: Start date or time.
  • end: End date or time.
  • periods: Number of periods to generate.
  • freq: Frequency of periods to generate.

Here is an example of how to use period_range() with a for loop:

import pandas as pd

start_date = '2020-01'
end_date = '2022-12'

quarters = pd.period_range(start=start_date, end=end_date, freq='Q')

for quarter in quarters:
    print(quarter)

Output:

2020Q1
2020Q2
2020Q3
2020Q4
2021Q1
2021Q2
2021Q3
2021Q4
2022Q1
2022Q2
2022Q3
2022Q4

In the above example, we first imported the pandas library and defined the start_date and end_date. We then used the period_range() function to create a range of quarters between the start_date and end_date. Finally, we used a for loop to iterate over the quarters and print each quarter.

Conclusion

In this guide, we covered how to use a for loop with pandas range. We showed examples using the date_range() and period_range() functions to create ranges of dates and periods, respectively. The for loop allows us to iterate over the range and perform operations on each element.