基于DataFrame两列4种组合,用嵌套np.where提取预计算列值
np.where to Map Before/After Combinations to Precomputed Columns Got it, let's work through this together. You've got a DataFrame with hundreds of groups, four distinct Before/After value pairs, and three precomputed columns—your goal is to generate an Output column that pulls values from the right precomputed column based on each row's Before/After combination. Nested np.where is perfect for this since it lets us chain conditional checks efficiently.
First, let's clarify the logic structure. We need to define which precomputed column corresponds to each of the four combinations. Let's assume your precomputed columns are named pre_col1, pre_col2, pre_col3 (adjust these names to match your actual data), and let's use a sample mapping (you can tweak this to match your specific requirements):
- Injection → Injection: Pull from
pre_col1 - Injection → Production: Pull from
pre_col2 - Production → Injection: Pull from
pre_col3 - Production → Production: Pull from
pre_col1(or whichever precomputed column you need for this case)
Here's how to implement this with nested np.where:
import numpy as np import pandas as pd # Example DataFrame (replace with your actual data) df = pd.DataFrame({ 'Group': ['G1'] * 4 + ['G2'] * 4, # Adding a second group to show scalability 'Before': ['Injection', 'Injection', 'Production', 'Production'] * 2, 'After': ['Injection', 'Production', 'Injection', 'Production'] * 2, 'pre_col1': [10, 20, 30, 40, 50, 60, 70, 80], 'pre_col2': [100, 200, 300, 400, 500, 600, 700, 800], 'pre_col3': [1000, 2000, 3000, 4000, 5000, 6000, 7000, 8000] }) # Nested np.where to generate Output column df['Output'] = np.where( # First condition: Injection → Injection (df['Before'] == 'Injection') & (df['After'] == 'Injection'), df['pre_col1'], # Second condition: Injection → Production np.where( (df['Before'] == 'Injection') & (df['After'] == 'Production'), df['pre_col2'], # Third condition: Production → Injection np.where( (df['Before'] == 'Production') & (df['After'] == 'Injection'), df['pre_col3'], # Final case: Production → Production (catch-all for remaining rows) df['pre_col1'] ) ) ) # Check the result print(df[['Group', 'Before', 'After', 'Output']])
How This Works:
- Each
np.whereacts as a conditional check: if the condition isTrue, it returns the second argument; ifFalse, it moves to the next nestednp.where. - The final
np.wherehandles the last remaining combination (Production → Production) since all other cases have already been checked. - This is a vectorized operation, so it's fast even with hundreds of groups and thousands of rows—no need for slow row-wise loops.
Just adjust the column names and the mapping of combinations to precomputed columns to fit your exact data, and you're good to go!
内容的提问来源于stack exchange,提问作者Quasar

