【问题标题】:how do i conduct an if statement using a numpy array我如何使用 numpy 数组执行 if 语句
【发布时间】:2020-04-04 22:30:25
【问题描述】:

我正在尝试创建一个程序以从 csv 文件中读取,然后将文件中的时间转换为一个 numpy 数组,以供 if 语句询问,如下所示:

from datetime import date, timedelta, datetime
import pandas as pd
import numpy as np

currentdate = date.today()

sevendaysago = currentdate - timedelta(days=7)

readings = pd.read_csv(r'C:\Users\Csaba\Downloads\BloodGlucoseData.csv')

blood_glucose_readings = readings["Historic Glucose mmol/L"]

dates_and_times = readings["Device Timestamp"]

reading_times_hours = dates_and_times.str.slice(10, 16)

reading_times = np.array(reading_times_hours)

reading_dates = dates_and_times.str.slice(0, 10)

morning_reading = 0

for reading in reading_times:
    if reading_times <= "4:00" and reading_times >= "11:00":
        morning_reading = morning_reading + 1

else:
    morning_reading = morning_reading

但是我仍然收到错误:

Traceback (most recent call last):
  File "C:\Users\Csaba\Documents\Python\Glucose Control Recommendation program.py", line 24, in <module>
    if reading_times <= "4:00" and reading_times >= "11:00":
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

感谢任何帮助

【问题讨论】:

  • 这能回答你的问题吗? Intersect two boolean arrays for True
  • 你希望这个做什么:for reading in reading_times: 你从来没有在循环中实际使用过reading
  • 我希望循环遍历 reading_times 数组中的每个读数,但不确定执行此操作的确切代码,对于 python 初学者来说,这个项目可能有点过于复杂,但我已经学会了自从我开始以来很多

标签: python arrays pandas numpy


【解决方案1】:

由于您正在迭代 reading_times,因此您应该在 if 语句中使用 reading,而不是 reading_times

for reading in reading_times:
    if reading <= "4:00" and reading >= "11:00":

reading_times 是一个数组,reading_times &lt;= "4:00" 也是。打印出来自己看看。像这样的数组不能用于if 语句,也不能用于and

else: 部分的缩进对吗?

【讨论】:

  • 非常感谢您完全修复了它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 1970-01-01
  • 2020-04-14
  • 1970-01-01
  • 1970-01-01
  • 2015-08-16
相关资源
最近更新 更多