首页 > 解决方案 > 将系列四舍五入到特定值,不是倍数?

问题描述

我正在尝试根据不是倍数的值列表对系列的值进行四舍五入。我试图四舍五入的值是 15、30、60 和 120。

您可以看到我不能使用 15 的倍数,因为这将包含 45、75、90...,我不想四舍五入。

语境

我正在做一个评估广播广告长度的项目。在无线电行业中,广告的长度通常为 15、30、60 或 120 秒。数据可能关闭的原因是跟踪软件标记了广告本身的开始和结束,而不是它假设的长度。因此,当广告被切断或跟踪软件意外跟踪下一个广告的一部分时,记录的长度会被丢弃。

我的代码

import pandas as pd

# Example of series I want to round
values_to_be_rounded = pd.Series([30, 101, 20, 48, 60])

# Values I want to round to
round_to_list = [15, 30, 60, 120]

# Create list of lists for the absolute difference between each index in round_to_list and values_to_be_rounded.
difference = [abs(values_to_be_rounded-round_to_list[0]), abs(values_to_be_rounded-round_to_list[1]),
              abs(values_to_be_rounded-round_to_list[2]), abs(values_to_be_rounded-round_to_list[3])]

# Turn into dataframe and transpose the data to set it up for the next part. 
# I name the headers the index value of round_to_list. 
# For example in the difference_df.iloc[0,0], that value is how far away 30 is from 15.
difference_df = pd.DataFrame(difference, index=[0, 1, 2, 3]).transpose()

# Get min value of each row
min_Value = difference_df.min(axis=1)

在这一部分,我试图检索每个最小值的标头,因为这是我需要确定round_to_list我应该舍入的值的索引。

解释示例

的值为difference_df.iloc[0, 1]0,将达到该行的最小值。这意味着标题为 1,是round_to_list我需要四舍五入的索引。在本例中为 30。

标签: pythonpython-3.xpandasrounding

解决方案


干得好:

data = pd.Series([30, 101, 20, 48, 60])
boundaries = pd.Series([15, 30, 60, 120])
print(data.map(lambda pt: boundaries[(boundaries - pt).abs().argmin()]))

输出:

0     30
1    120
2     15
3     60
4     60

推荐阅读