如何使用Numpy实现向最近的5取整并生成新B列
Got it, here's how you can round numbers to the nearest 5 using NumPy and store the result in a new column B. I'll walk through common scenarios below:
The core logic here is simple: divide your values by 5, round to the nearest integer, then multiply back by 5. NumPy makes this operation vectorized (fast even for large datasets) which is perfect for this task.
Scenario 1: Starting with a NumPy array and creating a DataFrame
If you have raw values in a NumPy array and want to turn them into a DataFrame with columns A (original) and B (rounded):
import numpy as np import pandas as pd # Your input data (replace with your actual array) raw_values = np.array([2, 7, 11, 16.5, 23, 28.4]) # Perform the rounding with NumPy rounded_vals = np.round(raw_values / 5) * 5 # Build the DataFrame df = pd.DataFrame({ 'A': raw_values, 'B': rounded_vals }) print(df)
Sample output:
A B 0 2.0 0.0 1 7.0 5.0 2 11.0 10.0 3 16.5 15.0 4 23.0 25.0 5 28.4 30.0
Scenario 2: Adding Column B to an existing DataFrame
If you already have a pandas DataFrame with a column (e.g., 'A') and want to append the rounded values as column B:
import numpy as np import pandas as pd # Existing DataFrame (replace with your actual data) df = pd.DataFrame({ 'A': [4, 9, 14, 19.2, 26, 32.7] }) # Add the rounded column using NumPy df['B'] = np.round(df['A'] / 5) * 5 print(df)
Sample output:
A B 0 4.0 5.0 1 9.0 10.0 2 14.0 15.0 3 19.2 20.0 4 26.0 25.0 5 32.7 30.0
Quick Note on Edge Cases
NumPy uses bankers rounding by default, which means when a value is exactly halfway between two multiples of 5, it rounds to the even multiple. For example:
2.5→ rounds to0(since 0 is even, halfway between 0 and 5)7.5→ rounds to10(halfway between 5 and 10, 10 is even)
If you prefer to always round up in these cases, swap np.round with np.ceil:
# Round up to nearest 5 df['B'] = np.ceil(df['A'] / 5) * 5
Or round down with np.floor if that's what you need.
内容的提问来源于stack exchange,提问作者Tie_24

