如何在pandas python中得到最近除以100的数字

如何在pandas python中得到最近除以100的数字,第1张

概述我想基于输入列在pandas数据框中添加一个新列.必须像这样填充新添加的列. >第一行必须填入最近除以100的数字. >从下一行开始,将重复输出,直到它与输入值的差值大于或等于100. input output11700.15 1170011695.20 1170011661.00 1170011630.40 1170011666.10 1170 我想基于输入列在pandas数据框中添加一个新列.必须像这样填充新添加的列.

>第一行必须填入最近除以100的数字.
>从下一行开始,将重复输出,直到它与输入值的差值大于或等于100.

input       output11700.15    1170011695.20    1170011661.00    1170011630.40    1170011666.10    1170011600.30    1170011600.00    1160011555.40    1160011655.20    1160011699.00    1160011701.55    1170011799.44    1170011604.65    1170011600.33    1170011599.65    11600

在熊猫中最优雅的做法是什么?

解决方法 据我所知,这里没有直观的方法,不涉及显式迭代,这对于numpy和pandas来说并不理想.但是,这个问题的时间复杂度是O(n),这使得它成为numba库的一个很好的目标.这使我们能够提出一个非常有效的解决方案.

关于我的解决方案的一个注意事项,我使用(阈值// 2)//阈值*阈值,与使用np.round(a,decimals = -2)相比看起来冗长.这是由于使用numba的nopython = True,flag的性质,它与np.round函数不兼容.

from numba import jit@jit(nopython=True)def cumsum_with_threshold(arr,threshold):       """       Rounds values in an array,propogating the last value seen until       a cumulative sum reaches a threshold       :param arr: the array to round and sum       :param threshold: the point at which to stop propogation       :return: rounded output array       """       s = a.shape[0]       o = np.empty(s)       d = a[0]       r = (a + threshold // 2) // threshold * threshold       c = 0       o[0] = r[0]       for i in range(1,s):           if np.abs(a[i] - d) > threshold:               o[i] = r[i]               d = a[i]           else:               o[i] = o[i - 1]       return o

我们来测试一下:

a = df['input'].valuespd.SerIEs(cumsum_with_threshold(a,100))
0     11700.01     11700.02     11700.03     11700.04     11700.05     11700.06     11600.07     11600.08     11600.09     11600.010    11700.011    11700.012    11700.013    11600.014    11600.0dtype: float64

如果要将舍入值与输入进行比较而不是实际值,只需在循环中对上面的函数进行以下更改,从而提供问题的输出.

for i in range(1,s):   if np.abs(a[i] - d) > t:       o[i] = r[i]       # olD d = a[i]       d = r[i]   else:       o[i] = o[i - 1]

为了测试效率,让我们在更大的数据集上运行它:

l = np.random.choice(df['input'].values,10_000_000)%timeit cumsum_with_threshold(l,100)1.54 µs ± 7.93 ns per loop (mean ± std. dev. of 7 runs,1000000 loops each)
总结

以上是内存溢出为你收集整理的如何在pandas python中得到最近除以100的数字全部内容,希望文章能够帮你解决如何在pandas python中得到最近除以100的数字所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1192194.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-03
下一篇 2022-06-03

发表评论

登录后才能评论

评论列表(0条)

保存