Slicing and Subsetting by Date
Veeg om het menu te tonen
12345678910111213141516171819import pandas as pd # Create a sample time series DataFrame dates = pd.date_range(start="2023-01-01", end="2023-06-30", freq="D") data = pd.DataFrame({ "value": range(len(dates)) }, index=dates) # Slicing using a date string: get all data for March 2023 march_data = data.loc["2023-03"] # Slicing using a date range: get data from January to March 2023 jan_to_mar_data = data["2023-01":"2023-03"] # Display results print("March 2023 data:") print(march_data.head()) print("\nData from January to March 2023:") print(jan_to_mar_data.tail())
Slicing and subsetting time series data by date is a core capability in pandas, making it easy to select relevant periods for analysis. When your DataFrame or Series has a DatetimeIndex, you can use date strings or ranges to quickly extract specific time windows. For instance, using a single month string like "2023-03" returns all rows from March 2023, while a range like "2023-01":"2023-03" selects data from January through March, inclusive. This approach is especially useful for tasks such as examining seasonal trends, focusing on specific periods for forecasting, or preparing training and testing datasets based on time. The syntax is both concise and readable, making your code more intuitive when working with temporal data.
Bedankt voor je feedback!
Vraag AI
Vraag AI
Vraag wat u wilt of probeer een van de voorgestelde vragen om onze chat te starten.