如何用Pandas datetime64创建自定义时间范围的销售日期归属列
Absolutely, you’re on the right track with adjusting dates based on transaction time—but stop using row-wise loops! That’s exactly why you’re hitting timeouts or crashing Jupyter. Pandas is built for vectorized operations (processing entire columns at once), which are way faster and more memory-efficient than looping through every row.
Here’s the clean, scalable way to handle your custom business date rule:
Step 1: Ensure Your Timestamp Column is Datetime Type
First, confirm NEW_TIMESTAMP is properly parsed as a datetime (skip this if it’s already in datetime format):
import pandas as pd import numpy as np df['NEW_TIMESTAMP'] = pd.to_datetime(df['NEW_TIMESTAMP'])
Step 2: Create the Business Date Column with Vectorized Logic
We’ll use Pandas’ built-in datetime properties and np.where to apply your rule in one go:
# Option 1: Return date objects (YYYY-MM-DD as a date type) df['business_date'] = np.where( df['NEW_TIMESTAMP'].dt.hour < 15, df['NEW_TIMESTAMP'].dt.date - pd.Timedelta(days=1), df['NEW_TIMESTAMP'].dt.date ) # Option 2: Return datetime objects (if you need to retain datetime format later) df['business_date'] = np.where( df['NEW_TIMESTAMP'].dt.hour < 15, df['NEW_TIMESTAMP'].dt.floor('D') - pd.Timedelta(days=1), df['NEW_TIMESTAMP'].dt.floor('D') )
Alternative: Explicit Assignment with .loc
If you prefer a more straightforward approach, initialize the business date to the transaction date first, then adjust the rows that fall in the 0–15 hour window:
df['business_date'] = df['NEW_TIMESTAMP'].dt.floor('D') # Subtract one day for transactions between midnight and 3 PM df.loc[df['NEW_TIMESTAMP'].dt.hour < 15, 'business_date'] -= pd.Timedelta(days=1)
Why This Works (And Your Loop Didn’t)
Row-wise loops (like for i in df.index:) force Pandas to process each record individually, which is slow and resource-heavy even for moderately sized datasets. Vectorized operations leverage optimized C-based code under the hood, so they run in a fraction of the time without crashing your environment.
You won’t find a "one-click" official function for this exact rule, but combining datetime properties with conditional vectorized logic is the standard Pandas approach for custom date adjustments like this.
内容的提问来源于stack exchange,提问作者Joshtralia

