在R中批量合并对应列:无需逐一操作生成新组合列
Hey there! I totally get the pain of manually merging 20 column pairs—let's fix that with a scalable, loop-based approach that'll handle all your pairs in one go.
First, Let's Set Up a Sample DataFrame
To make this concrete, here's a small example matching your structure (you can scale this to 20 pairs easily):
import pandas as pd # Sample DataFrame with 2 A-C pairs (replace with your actual data) df = pd.DataFrame({ 'A1': ['B1U', 'B2U'], 'A2': ['B1F', 'B2F'], 'C1': ['sweet', 'sour'], 'C2': ['dip', 'spread'] })
Method 1: Simple Loop for Explicit Column Pairs
If your columns follow a strict A1/A2/.../A20 and C1/C2/.../C20 naming pattern, this loop will directly pair each A column with its corresponding C column, then create a new combined column:
total_pairs = 20 # Match this to your actual number of column pairs for i in range(1, total_pairs + 1): # Define the current pair of columns a_col = f"A{i}" c_col = f"C{i}" # Name your new column (customize this to your preference) new_col_name = f"Combined_{i}" # Merge the values with an underscore (like your example: B1U_sweet) df[new_col_name] = df[a_col] + "_" + df[c_col]
Method 2: Flexible Pairing for Non-Standard Column Names
If your column names don't follow a strict numbering pattern (but still group into A and C categories), you can filter and sort the columns to pair them automatically:
# Get all A-starting columns, sorted to maintain order a_columns = sorted([col for col in df.columns if col.startswith('A')]) # Get all C-starting columns, sorted to match A column order c_columns = sorted([col for col in df.columns if col.startswith('C')]) # Iterate through each paired column set for a_col, c_col in zip(a_columns, c_columns): # Create a descriptive new column name (or use a custom pattern) new_col_name = f"{a_col}_{c_col}" # Combine the values df[new_col_name] = df[a_col] + "_" + df[c_col]
Method 3: Concise List Comprehension (Advanced)
For a more concise approach, you can generate all combined columns at once using a list comprehension, then add them to your DataFrame:
total_pairs = 20 # Generate all combined columns combined_columns = [df[f"A{i}"] + "_" + df[f"C{i}"] for i in range(1, total_pairs + 1)] # Add the new columns to the original DataFrame df = pd.concat([df] + combined_columns, axis=1) # Rename the new columns (optional but recommended) df.columns = list(df.columns[:-total_pairs]) + [f"Combined_{i}" for i in range(1, total_pairs + 1)]
All these methods will produce exactly what you need: new columns where each value is the concatenation of the corresponding A and C column values (e.g., B1U_sweet, B2F_dip). No more manual merging for each pair!
内容的提问来源于stack exchange,提问作者melbez

