如何在Python中根据ID匹配列名更新DataFrame对应值为0?
Since you're new to Python and pandas, let's break this down into simple, easy-to-understand methods. First, let's start by creating your sample DataFrame so you can test the code yourself:
import pandas as pd # Create your sample DataFrame data = { 'ID': ['ID_1', 'ID_2', 'ID_3', 'ID_4', 'ID_5'], 'ID_1': [1.0, 3.0, 7.0, 9.0, 11.0], 'ID_2': [20.1, 1.0, 70.1, 90.1, 10.1], 'ID_3': [31.0, 23.0, 1.0, 43.0, 11.0], 'ID_4': [23.1, 90.0, 23.0, 1.0, 23.0], 'ID_5': [31.5, 21.5, 31.5, 61.5, 1.0] } df = pd.DataFrame(data)
Method 1: Simple Loop (Easy to Understand)
This method uses a loop to go through each row, find the column that matches the row's ID value, and set that cell to 0. It's not the fastest for huge datasets, but it's straightforward for beginners to follow:
# Iterate over each row in the DataFrame for index, row in df.iterrows(): # Get the ID value from the current row matching_column = row['ID'] # Set the cell at this row and matching column to 0.0 df.loc[index, matching_column] = 0.0
Method 2: Vectorized Approach (Faster for Large Data)
If you're working with a bigger dataset, this method is more efficient. It uses pandas' built-in functions to avoid slow row-by-row loops:
# Loop through each column except the 'ID' column for column in df.columns[1:]: # Replace values with 0 where the row's ID matches the column name df[column] = df[column].where(df['ID'] != column, 0.0)
Method 3: Concise One-Liner (Pandas Idiomatic Style)
This one-liner uses apply to process each row and set the matching cell to 0. It's short and clean once you get the hang of pandas syntax:
df = df.apply(lambda row: row.assign(**{row['ID']: 0}), axis=1)
After running any of these methods, your DataFrame will match your expected output exactly:
| ID | ID_1 | ID_2 | ID_3 | ID_4 | ID_5 |
|---|---|---|---|---|---|
| ID_1 | 0.0 | 20.1 | 31.0 | 23.1 | 31.5 |
| ID_2 | 3.0 | 0.0 | 23.0 | 90.0 | 21.5 |
| ID_3 | 7.0 | 70.1 | 0.0 | 23.0 | 31.5 |
| ID_4 | 9.0 | 90.1 | 43.0 | 0.0 | 61.5 |
| ID_5 | 11.0 | 10.1 | 11.0 | 23.0 | 0.0 |
Quick Notes:
- All these methods work even if your rows aren't ordered by ID (unlike your sample where IDs match row order).
- The vectorized method (Method 2) is the best choice for large datasets because it's optimized for speed.
内容的提问来源于stack exchange,提问作者Sudipta Paul

