python - 遍历一系列以查找值 >= 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)
解决方案
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
推荐阅读
- python-3.x - 遍历元组列表
- ruby-on-rails - ActiveRecord 验证字符串,但能够将部分字符串视为整数
- python - 打开我的网络服务器时,浏览器显示 ERR_INVALID_HTTP_RESPONSE
- raspberry-pi - Raspberry pi - 将权限更改为 700
- javascript - framework7 react - 以编程方式切换选项卡
- python - node.js 发送 POST 请求以进行身份验证
- c# - 如何在 WPF 中将项目添加到 ListView
- c# - WPF 可观察集合
UI 框架元素嵌套 2 类深度 - javascript - 成员函数不能访问其成员属性?
- python - AttributeError:“PosixPath”对象没有属性“写”