I have a data frame with one column date, different person have different number of…
- User
I have a data frame with one column date, different person have different number of records in past 3 years. can you using python pandas to filter 1 year data from the latest date for each person
- Assistant
Yes, you can use pandas to filter one year data from the latest date for each person. Here is a sample code:
import pandas as pd # Create a sample data frame with 'date' and 'person' columns df = pd.DataFrame({'date': ['2021-08-01', '2021-07-01', '2020-08-01', '2020-07-01', '2019-08-01', '2019-07-01'], 'person': ['A', 'A', 'A', 'B', 'B', 'B']}) # Convert 'date' column to datetime format df['date'] = pd.to_datetime(df['date']) # Group the data frame by 'person' column and get the latest date for each person latest_dates = df.groupby('person')['date'].max() # Filter the data frame to include only the latest year data for each person one_year_data = pd.concat([df[(df['person'] == person) & (df['date'] >= latest_dates[person] - pd.DateOffset(years=1))] for person in latest_dates.index])In this code, we first convert the 'date' column to datetime format. Then, we group the data frame by 'person' column and get the latest date for each person using the
max()function. Finally, we use list comprehension andconcat()function to filter the data frame to include only the latest year data for each person. - User
This seems slow for large datasets, do you know other way?
- Assistant
Yes, you can also use Pandas apply() function to filter one year data from the latest date for each person. Here is an example code that utilizes apply() function.
import pandas as pd # Create a sample data frame with 'date' and 'person' columns df = pd.DataFrame({'date': ['2021-08-01', '2021-07-01', '2020-08-01', '2020-07-01', '2019-08-01', '2019-07-01'], 'person': ['A', 'A', 'A', 'B', 'B', 'B']}) # Convert 'date' column to datetime format df['date'] = pd.to_datetime(df['date']) # Define a function to filter data for each person def filter_data(group): latest_date = group['date'].max() one_year_ago = latest_date - pd.DateOffset(years=1) return group[group['date'] >= one_year_ago] # Filter the data frame to include only the latest year data for each person one_year_data = df.groupby('person').apply(filter_data).reset_index(drop=True)In this code, we first convert the 'date' column to datetime format. Then, we define a function to filter data for each person. Inside the function, we use function to get the latest date for the group, and then subtract one year to get the one-year-ago date. We use this date to filter the group and finally return the filtered group.