如何按向上取整规则筛选指定行并创建新df?求助
Hey Dan, let's work through this problem together to get your desired DataFrame sorted out!
Step 1: Clarify the rounding logic
First, we need to calculate the target C values based on your rounding rules for B:
- Round
Bup to the nearest multiple of 5: Usenp.ceil(B / 5) * 5(this gives 1135.0 in your example) - Round
Bup to the nearest multiple of 10: Usenp.ceil(B / 10) * 10(this gives 1140.0 in your example)
Step 2: Implement priority-based filtering
We'll first check for rows where C matches the 5-rounded target. If that returns an empty result (which is your current scenario), we'll fall back to the 10-rounded target. Here's a practical pandas/numpy implementation:
import pandas as pd import numpy as np # Replace this with your actual original DataFrame original_df = pd.DataFrame({ 'B': [1132, 1137], 'C': [1140.0, 1140.0] }) # Calculate the two target values for each row target_5 = np.ceil(original_df['B'] / 5) * 5 target_10 = np.ceil(original_df['B'] / 10) * 10 # First attempt: filter rows where C matches the 5-rounded target new_df = original_df[original_df['C'] == target_5] # If no rows are found, switch to the 10-rounded target if new_df.empty: new_df = original_df[original_df['C'] == target_10] print(new_df)
Quick notes to avoid issues
- Double-check that columns
BandCare numeric types (useoriginal_df.dtypesto verify) - If you're working with a single specific value of
B(not an entire column), calculate the targets directly with that value instead of using the column - This code handles row-wise checks—if you need to filter based on a global target (e.g., round one B value once and find all matching C rows), just adjust the target calculation to use that single value
内容的提问来源于stack exchange,提问作者Dan_99
相关产品推荐
相关产品推荐

