You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python是否有类似Godot stepify的numpy数组、Series网格对齐函数?

Python生态下Godot stepify功能的实现方案

你要的均匀步长对齐功能不需要自行实现,用numpy、pandas的基础运算即可直接实现,同时支持标量、numpy数组、pandas Series的批量处理,底层逻辑和Godot的stepify完全一致:

stepify核心逻辑:将输入值除以步长后四舍五入,再乘以步长,公式为 round(s / step) * step

1. numpy实现示例

numpy的向量化运算天然支持数组批量处理,不需要额外循环:

import numpy as np

# 标量计算,和Godot示例结果完全一致
print(np.round(100 / 32) * 32)       # 输出 96.0
print(np.round(3.14159 / 0.01) * 0.01) # 输出 3.14

# numpy数组批量处理
arr = np.array([100, 3.14159, 52, 2.71828])
step = 32 # 全局统一步长
print(np.round(arr / step) * step)
# 输出 [96.  0. 64.  0.]

# 也支持每个元素对应不同步长
step_arr = np.array([32, 0.01, 16, 0.001])
print(np.round(arr / step_arr) * step_arr)
# 输出 [96.    3.14  48.    2.718]

2. pandas Series实现示例

pandas的Series也支持直接用同样的逻辑批量计算:

import pandas as pd

s = pd.Series([100, 3.14159, 52, 2.71828])
step = pd.Series([32, 0.01, 16, 0.001])
res = (s / step).round() * step
print(res)
# 0    96.000
# 1     3.140
# 2    48.000
# 3     2.718
# dtype: float64

拓展调整

如果需要向下对齐到步长网格(取小于等于输入值的最近网格点),把round替换为floor即可;如果需要向上对齐,替换为ceil即可。

内容的提问来源于stack exchange,提问作者ascripter

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 10:27:04