如何利用DataFrame某列数值作为列索引从另一DataFrame选列
Solution to Select and Rename Columns from df2 Using df1's Values
Got it, let's walk through how to solve this problem clearly. Here's what we need to do: pick columns from df2 that match the numbers in df1's Col1, then rename those columns to the "Col X" format you want.
Step-by-Step Implementation
First, let's set up some sample data to test with (you can replace this with your actual DataFrames):
import pandas as pd import numpy as np # Your original df1 df1 = pd.DataFrame({ 'Col1': [10, 5, 7, 1, 3], 'Col2': [100, 90, 87, 83, 70] }) # Sample df2 with columns Col1 to Col20 df2 = pd.DataFrame( np.random.randint(0, 100, size=(5, 20)), # 5 rows, 20 columns of random numbers columns=[f"Col{i}" for i in range(1, 21)] )
Now, let's execute the core logic:
# 1. Generate the exact column names we need from df2 # Convert each number in df1['Col1'] to "ColX" (e.g., 10 → "Col10") target_columns = [f"Col{num}" for num in df1['Col1']] # 2. Select those columns from df2 selected_data = df2[target_columns] # 3. Rename the columns to "Col X" format (e.g., "Col10" → "Col 10") # Option 1: Using a lambda function for quick renaming result_df = selected_data.rename(columns=lambda col: f"Col {col[3:]}") # Option 2: Using a dictionary (more explicit for beginners) # rename_mapping = {old_col: f"Col {old_col.split('Col')[1]}" for old_col in target_columns} # result_df = selected_data.rename(columns=rename_mapping) # Check the result print(result_df)
What Each Part Does
target_columns: We take every number from df1'sCol1and format it to match df2's column naming convention (since df2 uses "Col1", "Col2", etc.). This ensures we pick the correct columns from df2.df2[target_columns]: This selects the columns from df2 in the same order as the numbers appear in df1'sCol1(so first Col10, then Col5, etc.).- Renaming: We adjust the column names by adding a space between "Col" and the number. The lambda function takes each column name, slices off the first 3 characters ("Col"), then appends that number to "Col ". The dictionary approach does the same thing but is more explicit if you want to see exactly what's being renamed.
Example Output
If you run the code, you'll get a DataFrame that looks like this (values will vary since we used random numbers):
Col 10 Col 5 Col 7 Col 1 Col 3 0 45 23 78 12 67 1 89 56 34 90 21 2 11 44 66 33 55 3 77 88 99 10 20 4 30 40 50 60 70
内容的提问来源于stack exchange,提问作者noob
相关产品推荐
相关产品推荐

