Pandas中如何优雅按条件用两列最大值填充Plan Date列?
Elegant Solution to Fill Plan Date Based on Plan Deadline Condition
Got it, let's tackle this problem with a clean, pandas-native approach that's way more elegant than using np.where(). First, let's make sure we're working with a properly formatted DataFrame (I converted the nanosecond timestamps in Plan Date to proper datetime objects for consistency):
import pandas as pd import numpy as np # Your original data converted to a usable DataFrame df = pd.DataFrame({ "Plan Date": {23186: np.nan, 18533: np.nan, 17980: np.nan, 28559: np.nan, 22587: 1572480000000000000, 22522: 1580428800000000000, 16639: 1572480000000000000, 14304: 1572480000000000000}, "Support Date": {23186: pd.Timestamp('2020-12-31'), 18533: pd.Timestamp('2022-03-31'), 17980: pd.Timestamp('2022-03-31'), 28559: pd.Timestamp('2019-02-28'), 22587: pd.Timestamp('2019-07-31'), 22522: pd.Timestamp('2019-07-31'), 16639: pd.Timestamp('2019-10-31'), 14304: pd.Timestamp('2019-10-31')}, "Plan Deadline": {23186: pd.NaT, 18533: pd.NaT, 17980: pd.NaT, 28559: pd.NaT, 22587: pd.Timestamp('2019-10-31'), 22522: pd.Timestamp('2020-01-31'), 16639: pd.Timestamp('2019-10-31'), 14304: pd.Timestamp('2019-10-31')} }) # Convert nanosecond timestamps in Plan Date to datetime df['Plan Date'] = pd.to_datetime(df['Plan Date'])
The Cleanest Approach: Use loc + max(axis=1)
Instead of clunky np.where() logic, we can leverage pandas' native indexing and row-wise max calculation to achieve exactly what you need:
# Only fill Plan Date where Plan Deadline is not missing df.loc[df['Plan Deadline'].notna(), 'Plan Date'] = df[['Support Date', 'Plan Deadline']].max(axis=1)
Why This Works:
- Precise Indexing:
df.loc[df['Plan Deadline'].notna(), 'Plan Date']targets exactly the rows and column we need to modify—no unnecessary operations on the entire DataFrame. - Row-Wise Max:
df[['Support Date', 'Plan Deadline']].max(axis=1)calculates the maximum date for each row across the two columns, which is exactly what we want to put intoPlan Date. - Readability: The code reads like plain English, making it easy for anyone to understand the logic at a glance.
Result After Processing:
Plan Date Support Date Plan Deadline 23186 NaT 2020-12-31 NaT 18533 NaT 2022-03-31 NaT 17980 NaT 2022-03-31 NaT 28559 NaT 2019-02-28 NaT 22587 2019-10-31 2019-07-31 2019-10-31 22522 2020-01-31 2019-07-31 2020-01-31 16639 2019-10-31 2019-10-31 2019-10-31 14304 2019-10-31 2019-10-31 2019-10-31
Bonus: Non-Destructive Version
If you don't want to modify the original DataFrame, just create a copy first:
new_df = df.copy() new_df.loc[new_df['Plan Deadline'].notna(), 'Plan Date'] = new_df[['Support Date', 'Plan Deadline']].max(axis=1)
内容的提问来源于stack exchange,提问作者Bartek Malysz
相关产品推荐
相关产品推荐

