You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中根据ID匹配列名更新DataFrame对应值为0?

How to Set Matching ID Column Cells to 0 in Pandas

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:

IDID_1ID_2ID_3ID_4ID_5
ID_10.020.131.023.131.5
ID_23.00.023.090.021.5
ID_37.070.10.023.031.5
ID_49.090.143.00.061.5
ID_511.010.111.023.00.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.11 08:14:00