如何将DataFrame的D列与numpy ndarray比较并更新E列值?
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:
Method 1: Use isin() (Recommended)
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

