如何在R中基于月份,利用多DataFrame创建匹配ID的矩阵
Hey there! Let's work through this problem step by step. From what I understand, you've got 8 DataFrames, and you need to build a matrix where we use only the dates and months from DF_1 as the baseline, while the other DataFrames only match data by the ID column. Here's a practical, pandas-based approach tailored to this need:
First, we'll extract the month information from DF_1's date column and create a skeleton matrix that pairs all relevant IDs with DF_1's unique months.
import pandas as pd # Extract month from DF_1's date column (adjust format to your needs) # 'YYYY-MM' period format is great for clear month-year grouping DF_1['month'] = DF_1['date'].dt.to_period('M') # If you prefer just numeric month (1-12): DF_1['month'] = DF_1['date'].dt.month # Get all unique IDs across your 8 DataFrames (or use only DF_1's IDs if that's your requirement) all_dfs = [DF_1, DF_2, DF_3, DF_4, DF_5, DF_6, DF_7, DF_8] unique_ids = pd.concat([df['id'] for df in all_dfs]).unique() # Create base matrix: cross product of unique IDs and DF_1's unique months base_matrix = pd.MultiIndex.from_product( [unique_ids, DF_1['month'].unique()], names=['id', 'month'] ).to_frame(index=False)
Next, we'll merge each DataFrame's data into the base matrix. For DF_1, we'll match on both ID and month (since it's our baseline), while for all other DataFrames, we'll only match on ID.
# Merge DF_1's data (matches on both ID and month) # Replace 'metric_1' with your actual column name from DF_1 base_matrix = base_matrix.merge( DF_1[['id', 'month', 'metric_1']], on=['id', 'month'], how='left' ) # Merge data from DF_2 to DF_8 (only match on ID) # Repeat this pattern for each remaining DataFrame base_matrix = base_matrix.merge( DF_2[['id', 'metric_2']], on='id', how='left' ) base_matrix = base_matrix.merge(DF_3[['id', 'metric_3']], on='id', how='left') base_matrix = base_matrix.merge(DF_4[['id', 'metric_4']], on='id', how='left') base_matrix = base_matrix.merge(DF_5[['id', 'metric_5']], on='id', how='left') base_matrix = base_matrix.merge(DF_6[['id', 'metric_6']], on='id', how='left') base_matrix = base_matrix.merge(DF_7[['id', 'metric_7']], on='id', how='left') base_matrix = base_matrix.merge(DF_8[['id', 'metric_8']], on='id', how='left')
If you want a pivot-style matrix where rows are IDs and columns are months (for metrics tied to DF_1's dates), use the pivot method:
# Pivot for DF_1's metric (will show values per ID-month pair) metric_1_month_matrix = base_matrix.pivot(index='id', columns='month', values='metric_1') # For other metrics (which are ID-only), you can create a simplified matrix metric_2_id_matrix = base_matrix[['id', 'metric_2']].drop_duplicates().set_index('id')
- Replace column names like
date,id,metric_Xwith your actual DataFrame column labels. - If you only want IDs that exist in DF_1, replace
unique_idswithDF_1['id'].unique(). - Use
fillna()to handle missing values (e.g.,base_matrix.fillna(0, inplace=True)to replace NaNs with 0).
内容的提问来源于stack exchange,提问作者Rahul shah

