在R语言中循环合并同数字后缀的二进制列生成新列
Solution to Merge Binary Columns by Numeric Suffix (Row-Wise)
Got it, let's walk through how to solve this problem. You need to combine columns that share the same numeric suffix into new string columns, with each row's values merged independently. Here's a practical implementation using pandas:
Step 1: Set Up the Example DataFrame
First, let's recreate your sample data to test with:
import pandas as pd # Build the sample DataFrame as described data = { 'A1': [1, 1], 'B1': [0, 0], 'C1': [0, 0], 'D1': [1, 1], 'A2': [0, 1], 'B2': [1, 1], 'C2': [1, 1], 'D2': [0, 0] } df = pd.DataFrame(data, index=['row1', 'row2'])
Step 2: Merge Columns by Suffix
We'll extract the numeric suffixes from column names, group columns by these suffixes, then merge each row's values into a string:
# Get all unique numeric suffixes from column names unique_suffixes = sorted(set(col[-1] for col in df.columns)) # Loop through each suffix to create merged columns for suffix in unique_suffixes: # Filter columns that end with the current suffix target_cols = [col for col in df.columns if col.endswith(suffix)] # Optional: Sort columns to ensure consistent order (e.g., A1 → B1 → C1 → D1) target_cols = sorted(target_cols) # Merge each row's values into a string (convert to str first, then join) df[f'newCol{suffix}'] = df[target_cols].astype(str).apply(''.join, axis=1) # Keep only the new merged columns (adjust if you want to retain original columns) final_df = df.filter(like='newCol') print(final_df)
Output Result
Running the code above will give you exactly the output you're looking for:
newCol1 newCol2 row1 1001 0110 row2 1001 1110
Key Notes
- Row-wise independence: The
apply(''.join, axis=1)ensures we process each row individually, merging its values without affecting other rows. - Column order: Sorting
target_colsguarantees we merge columns in alphabetical order (A1 before B1, etc.)—remove this line if you want to keep the original column order. - Scalability: This code works for any number of suffixes (not just 1 and 2) as long as your column names follow the
[Letter][Number]format.
内容的提问来源于stack exchange,提问作者Zer0
相关产品推荐
相关产品推荐

