首页 > 解决方案 > 遍历一系列以查找值 >= x 然后使用值

问题描述

我通过阅读 .xlsx 电子表格创建了一系列(长度为 201),如下所示:

xl = pandas.ExcelFile(file)
data = xl.parse('Sheet1')
data.columns = ["a", "b", "c", "d", "e", "f", "g", "h"]
A = data.a

所以我正在和 A 一起工作,如果print (A)我得到

0      76.0
1      190.0
2      0.0
3      86.0
4      0.0

196    156.0
197    0.0
198    0.0
199    320.0
200    0.0
Name: Vazi, Length: 201, dtype: float64

我想遍历 A 并找到所有值 => 180 并创建一个新数组(或系列),其中对于 A => 180 中的值,我减去 180,但对于 A =< 180 中的值,我使用原始值。我尝试了以下方法,但出现错误:

nx = len(A)
for i in range (nx):
    if A_new(i) >= A(i) + 180:
        else A_new(i) == A(i)

标签: pythonpython-3.xpandasiterationseries

解决方案


使用Series.mask/ Series.where

new_s = s.mask(s.ge(180),s.sub(180))
#new_s = s.sub(180).where(s.ge(180),s) #or series.where

或者np.where

new_s = pd.Series(data = np.where(s.ge(180),s.sub(180),s),
                  index = s.index,
                  name = s.name)

我们也可以使用Series.loc

new_s = s.copy()
new_s.loc[s.ge(180)] =s.sub(180)

new_s 输出

0       76.0
1       10.0
2        0.0
3       86.0
4        0.0
196    156.0
197      0.0
198      0.0
199    140.0
200      0.0
Name: Vazi, Length: 201, dtype: float64

推荐阅读