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

如何将DataFrame的D列与numpy ndarray比较并更新E列值?

Pandas: Update Column Based on Value Match with Numpy Array

Got it, let's solve this Pandas and numpy matching problem step by step!

Problem Statement

Suppose we have this Pandas DataFrame df:

A   B   C   D          E
0  1   2   4   6  该列需更新
1 12  34   5  54           
2  4   8  12   4           
3  3   5   6   2           
4  5   7  11  27           

And a numpy ndarray npar with shape (4,1):

npar = np.array([[12], [6], [2], [27]])

We need to update the E column in df: if the value in column D exists anywhere in npar, set E to 1; otherwise, set it to 0.

Solution Code

Here are two straightforward and efficient ways to get this done:

This is the most concise and performant approach. First, we flatten the 2D numpy array to a 1D array, then use Pandas' isin() method to check for matches, and convert the boolean results to integers (since True maps to 1 and False maps to 0):

import pandas as pd
import numpy as np

# Create the sample DataFrame
df = pd.DataFrame({
    'A': [1, 12, 4, 3, 5],
    'B': [2, 34, 8, 5, 7],
    'C': [4, 5, 12, 6, 11],
    'D': [6, 54, 4, 2, 27],
    'E': ['该列需更新', '', '', '', '']
})

# Create the sample numpy array
npar = np.array([[12], [6], [2], [27]])

# Update the E column
df['E'] = df['D'].isin(npar.flatten()).astype(int)

# Print the result to verify
print(df)

Method 2: Use apply() with any()

If you prefer a more explicit row-wise check (good for understanding the logic), you can use apply() with a custom function that checks if each value in column D exists in the numpy array:

# Same setup for df and npar as above

def check_match(val):
    # Check if the value is present anywhere in the numpy array
    return 1 if (npar == val).any() else 0

# Apply the function to column D and update E
df['E'] = df['D'].apply(check_match)

# Print the result
print(df)

Final Output

Both methods will produce the following updated DataFrame, where E is correctly set to 1 for matching values and 0 otherwise:

A   B   C   D  E
0  1   2   4   6  1
1 12  34   5  54  0
2  4   8  12   4  0
3  3   5   6   2  1
4  5   7  11  27  1

内容的提问来源于stack exchange,提问作者ASING

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.26 09:02:33