numpy教程:逻辑函数Logic functions

本文介绍了NumPy库中用于逻辑运算和数组比较的各种函数,包括all、any、logical_and等逻辑操作,以及isclose、allclose等比较函数。同时涵盖了如何判断数组是否为空、是否包含特定值的方法。

http://blog.youkuaiyun.com/pipisorry/article/details/48208433

真值测试Truth value testing

all(a[, axis, out, keepdims])Test whether all array elements along a given axis evaluate to True.
any(a[, axis, out, keepdims])Test whether any array element along a given axis evaluates to True.

只要数组中有一个值为True,则any()返回True;而只有数组的全部元素都为True,all()才返回True。

也可以直接当成array数组的方法使用。

判断numpy数组是否为空

if a.size:
 print('array is not empty')

如果通过python列表,把一个列表作为一个布尔值会产生True如果有项目,False如果它是空的。
lst = []
if lst:
 print "array has items"
if not lst:
 print "array is empty"

[Python的-如何检查数组不为空?]

判断numpy数组中是否有True

array.any()

皮皮blog


数组内容Array contents

isfinite(x[, out])Test element-wise for finiteness (not infinity or not Not a Number).
isinf(x[, out])Test element-wise for positive or negative infinity.
isnan(x[, out])Test element-wise for NaN and return result as a boolean array.
isneginf(x[, y])Test element-wise for negative infinity, return result as bool array.
isposinf(x[, y])Test element-wise for positive infinity, return result as bool array.

numpy.isnan

numpy判断一个元素是否为np.NaN,判断某元素是否是nan

numpy.isnan(element)

Note: 不能使用array[0] == np.NaN,总是返回False!

numpy数组元素替换numpy.nan_to_num(x)

判断某元素是否是nan,inf,neginf,如果是,nan换为0,inf换为一个非常大的数,neginf换为非常小的数

numpy.nan_to_num(x)
Replace nan with zero and inf with finite numbers.
Returns an array or scalar replacing Not a Number (NaN) with zero, (positive) infinity with a very large number and negative infinity with a very small (or negative) number.


数组类型测试Array type testing

iscomplex(x)Returns a bool array, where True if input element is complex.
iscomplexobj(x)Check for a complex type or an array of complex numbers.
isfortran(a)Returns True if the array is Fortran contiguous but not C contiguous.
isreal(x)Returns a bool array, where True if input element is real.
isrealobj(x)Return True if x is a not complex type or an array of complex numbers.
isscalar(num)Returns True if the type of num is a scalar type.


逻辑操作Logical operations

logical_and(x1, x2[, out])Compute the truth value of x1 AND x2 element-wise.
logical_or(x1, x2[, out])Compute the truth value of x1 OR x2 element-wise.
logical_not(x[, out])Compute the truth value of NOT x element-wise.
logical_xor(x1, x2[, out])Compute the truth value of x1 XOR x2, element-wise.

两个0-1array相与操作

判断两个0-1array有多少个相同的1, 两种方式

rate = np.count_nonzero(np.logical_and(fs_predict_array, ground_truth_array))
rate = np.count_nonzero(fs_predict_array * ground_truth_array)
不过fs_predict_array * ground_truth_array返回的是0-1array,而np.logical_and(fs_predict_array ,ground_truth_array)返回的是True-False array,但是都可以使用sum()得到1或者True的数目。

lz亲测下面的logical_and操作运行速度更快,没有count_nonzero会更快。

皮皮blog


比较Comparison

allclose(a, b[, rtol, atol, equal_nan])Returns True if two arrays are element-wise equal within a tolerance.
isclose(a, b[, rtol, atol, equal_nan])Returns a boolean array where two arrays are element-wise equal within a tolerance.
array_equal(a1, a2)True if two arrays have the same shape and elements, False otherwise.
array_equiv(a1, a2)Returns True if input arrays are shape consistent and all elements equal.
greater(x1, x2[, out])Return the truth value of (x1 > x2) element-wise.
greater_equal(x1, x2[, out])Return the truth value of (x1 >= x2) element-wise.
less(x1, x2[, out])Return the truth value of (x1 < x2) element-wise.
less_equal(x1, x2[, out])Return the truth value of (x1 =< x2) element-wise.
equal(x1, x2[, out])Return (x1 == x2) element-wise.
not_equal(x1, x2[, out])Return (x1 != x2) element-wise.
allclose

如果两个数组在tolerance误差范围内相等,则返回True。

from: http://blog.youkuaiyun.com/pipisorry/article/details/48208433

ref: Logic functions


初始化失败: 'int' object has no attribute 'text'import time import sys import threading from PyQt5.QtWidgets import * from PyQt5.QtCore import * from PyQt5.uic import loadUi from datetime import datetime, timedelta import ctypes import numpy as np import pandas as pd import msvcrt import queue import matplotlib.pyplot as plt from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas sys.path.append(r"../../../") from ART_SCOPE_Lib.functions import Functions from ART_SCOPE_Lib.constants import * from ART_SCOPE_Lib.lib import * from ART_SCOPE_Lib.errors import check_for_error, ArtScopeError class MyWindows(QMainWindow): def __init__(self): super(MyWindows, self).__init__() loadUi('./fff1.ui', self) # 获取已有的 QLineEdit 控件的引用 self.minSampleRate = self.findChild(QLineEdit, 'minSampleRate') self.column_count_limit = self.findChild(QLineEdit, 'column_count_limit') self.acquisit_break = self.findChild(QLineEdit, 'acquisit_break') self.channel_number = self.findChild(QLineEdit, 'channel_number') # 初始化UI元素,设置默认值 self.minSampleRate.setText('50000') # 默认采样率为50000 self.acquisit_break.setText('30') # 默认采集时长为30秒 self.column_count_limit.setText('10') # 默认列计数器为10 self.channel_number.setText('1') # 默认通道1 # 获取已有的widget控件 self.widget_1 = self.findChild(QWidget, 'widget') # 获取ui文件中的widget控件 self.widget_2 = self.findChild(QWidget, 'widget_2') # 获取ui文件中的widget控件 # 创建matplotlib图形并嵌入widget控件 self.fig_1, self.ax_1, self.canvas_1 = self.embed_plot(self.widget_1) self.fig_2, self.ax_2, self.canvas_2 = self.embed_plot(self.widget_2) # 设置 matplotlib 使用的字体 plt.rcParams['font.sans-serif'] = ['SimSun', 'Microsoft YaHei'] # 使用宋体和微软雅黑 plt.rcParams['axes.unicode_minus'] = False # 解决负号显示问题 self.timer = None # 定义一个定时器 self.acquisit_2.clicked.connect(self.f_initial) self.acquisit_3.clicked.connect(self.f_data) def f_initial(self): try: print(type(self.channel_number.text())) self.min_sample_rate = int(self.minSampleRate.text()) # 获取采样率 self.column_count_limit = int(self.column_count_limit.text()) # 获取列计数限制 self.acquisit_break = int(self.acquisit_break.text()) # 获取采集时长 self.channel_number = int(self.channel_number.text()) # 设置通道数 print(self.channel_number) self.led2.setStyleSheet("QLabel { background-color: red }") time.sleep(0.2) except Exception as e: print(f"初始化失败: {e}") def f_begin(self): try: self.f_initial() # 创建用于存放fft数据的队列 self.data_queue = queue.Queue() self.data_queue_2 = queue.Queue() # 创建第二个队列,用于数据保存 # 启动FFT和数据保存线程 self.fft_thread = threading.Thread(target=self.fft_logic) self.fft_thread.daemon = True # 设置为守护线程 self.fft_thread.start() self.data_flag = 1 self.column_count_flag = 1 self.data_thread = threading.Thread(target=self.data_logic) self.data_thread.daemon = True # 设置为守护线程 self.data_thread.start() # 在单独的线程中启动采集 self.acquisition_thread = threading.Thread(target=self.acquisition_logic) self.acquisition_thread.start() self.led2.setStyleSheet("QLabel { background-color: green }") except Exception as e: print(f"开始采集失败: {e}") def f_data(self): if self.timer is not None and self.timer.isActive(): return # 如果定时器还在运行,则不再执行 # 启动定时器,延迟1秒后执行代码 self.timer = QTimer(self) self.timer.setSingleShot(True) # 设置定时器为单次触发 self.timer.timeout.connect(self.handle_button_click) # 设置延时后的处理函数 self.timer.start(500) # 延时500毫秒(0.5秒) def handle_button_click(self): if self.data_flag: self.data_flag = 0 if not self.data_queue_2.empty(): x = self.data_queue_2.get() #清除队列2 print("停止保存") self.led2.setStyleSheet("QLabel {background-color: red}") else: self.column_count = 0 self.data_flag = 1 print("开始保存") self.led2.setStyleSheet("QLabel { background-color: green}") def acquisition_logic(self): try: taskName = 'Dev1' # 设备名称 taskHandle = lib_importer.task_handle(0) # 任务句柄 self.taskHandle_close = taskHandle # 创建任务 error_code = Functions.ArtScope_init(taskName, taskHandle) if error_code < 0: check_for_error(error_code) # 设置采集模式 acquisitionMode = SampleMode.CONTINUOUS error_code = Functions.ArtScope_ConfigureAcquisitionMode(taskHandle, acquisitionMode) self.data_queue = queue.Queue(maxsize=self.min_sample_rate * self.channel_number) self.data_queue_2 = queue.Queue(maxsize=self.min_sample_rate * self.channel_number) # 设置垂直参数 if self.channel_number == 1: channelName = '0' elif self.channel_number == 2: channelName = '0,1' elif self.channel_number == 3: channelName = '0,1,2' else: channelName = '0,1,2,3' # 通道名称 verticalRange = InputRange.RANGE_10VPP # 范围 verticalOffset = 0 # 偏移 verticalCoupling = CouplingType.DC # 耦合 probeAttenuation = 1 # 未使用 enabled = 1 # 通道启用 error_code = Functions.ArtScope_ConfigureVertical(taskHandle, channelName, verticalRange, verticalOffset, verticalCoupling, probeAttenuation, enabled) if error_code < 0: Functions.ArtScope_Close(taskHandle) check_for_error(error_code) # 设置水平参数 refPosition = 0 # 触发位置 error_code = Functions.ArtScope_ConfigureHorizontalTiming(taskHandle, self.min_sample_rate, self.min_sample_rate, refPosition) if error_code < 0: Functions.ArtScope_Close(taskHandle) check_for_error(error_code) # 设置软件触发 error_code = Functions.ArtScope_ConfigureTriggerSoftWare(taskHandle) # 获取实际通道数 numWfms = ctypes.c_uint32(0) error_code = Functions.ArtScope_ActualNumWfms(taskHandle, numWfms) if error_code < 0: Functions.ArtScope_Close(taskHandle) check_for_error(error_code) # 初始化采集 error_code = Functions.ArtScope_InitiateAcquisition(taskHandle) if error_code < 0: Functions.ArtScope_Close(taskHandle) check_for_error(error_code) # 获取实际样本长度 actualRecordLength = ctypes.c_uint32(0) error_code = Functions.ArtScope_ActualRecordLength(taskHandle, actualRecordLength) if error_code < 0: Functions.ArtScope_Close(taskHandle) check_for_error(error_code) # 数据缓冲区 sumLength = actualRecordLength.value * numWfms.value waveformPtr = np.zeros(self.min_sample_rate*self.channel_number, dtype=np.double) # 启动采集 error_code = Functions.ArtScope_StartAcquisition(taskHandle) if error_code < 0: Functions.ArtScope_ReleaseAcquisition(taskHandle) Functions.ArtScope_Close(taskHandle) check_for_error(error_code) timeout = 5.0 # 超时时间(单位:秒) readLength = actualRecordLength wfmInfo = ArtScope_wfmInfo() # 分析信息 wfmInfo.actualSamples = 0 wfmInfo.pAvailSampsPoints = 0 self.column_count = 0 # 采集循环 while True: error_code = Functions.ArtScope_FetchVoltage(taskHandle, timeout, readLength, waveformPtr, wfmInfo) if error_code < 0: Functions.ArtScope_StopAcquisition(taskHandle) Functions.ArtScope_Close(taskHandle) check_for_error(error_code) self.data_queue.put(waveformPtr[:self.min_sample_rate]) # 传到fft self.column_count = self.column_count + 1 if self.data_flag and self.column_count < self.column_count_limit: self.data_queue_2.put(waveformPtr[:]) # 传到保存队列 elif self.data_flag and self.column_count == self.column_count_limit: self.start_time = datetime.now() self.data_queue_2.put(waveformPtr[:]) # 传到保存队列 elif self.data_flag and self.column_count == self.acquisit_break: self.column_count = 0 except Exception as e: print(f"数据逻辑失败: {e}") def data_logic(self): try: df_auto = pd.DataFrame() while True: while self.data_flag: if not self.data_queue_2.empty(): df_auto[f"Waveform {self.column_count}"] = self.data_queue_2.get() # 将waveformPtr幅值给新的列 print(self.column_count) # 每column_count_limit个波形后保存数据 if self.column_count == self.column_count_limit: begin_time = (self.start_time- timedelta(seconds=self.column_count_limit)).strftime("%Y-%m-%d_%H-%M-%S") f_name = f"{begin_time}.xlsx" df_auto.to_excel(f_name, index=False) print(f"数据已保存到 {f_name}") df_auto = pd.DataFrame() except Exception as e: print(f"数据逻辑失败: {e}") def fft_logic(self): while True: if not self.data_queue.empty(): data = self.data_queue.get() self.ax_2.clear() time_axis = np.linspace(0, 1, self.min_sample_rate) # 创建时间轴,从 0 到 1 秒 self.ax_2.plot(time_axis, data[:self.min_sample_rate]) # 绘制时域信号 self.canvas_2.draw() # 更新显示 # 执行傅里叶变换 fft_result = np.fft.fft(data[:self.min_sample_rate]) fft_freq = np.fft.fftfreq(self.min_sample_rate, d=1.0 / self.min_sample_rate) # 计算频率 mask = (fft_freq >= 1000) & (fft_freq <= self.min_sample_rate / 2) filtered_fft_freq = fft_freq[mask] filtered_fft_result = np.abs(fft_result[mask]) # 更新图形 self.ax_1.clear() # 清除当前的图形 self.ax_1.plot(filtered_fft_freq, filtered_fft_result) self.canvas_1.draw() # 更新显示 time.sleep(0.1) # 短暂休眠,避免过度占用CPU def embed_plot(self, widget): # 初始化GUI绘图 try: self.fig, self.ax = plt.subplots() self.canvas = FigureCanvas(self.fig) layout = QVBoxLayout(widget) layout.addWidget(self.canvas) return self.fig, self.ax, self.canvas except Exception as e: print(f"嵌入绘图失败: {e}") def f_close(self): try: # 停止采集 self.led2.setStyleSheet("QLabel { background-color: red }") """ error_code = Functions.ArtScope_StopAcquisition(self.taskHandle_close) if error_code < 0: Functions.ArtScope_ReleaseAcquisition(self.taskHandle_close) Functions.ArtScope_Close(self.taskHandle_close) # 释放采集 error_code = Functions.ArtScope_ReleaseAcquisition(self.taskHandle_close) if error_code < 0: Functions.ArtScope_Close(self.taskHandle_close) # 关闭任务 error_code = Functions.ArtScope_Close(self.taskHandle_close) if error_code < 0: raise ArtScopeError("关闭任务失败") """ # 显示退出确认对话框 reply = QMessageBox.question(self, '退出', '确定要退出程序吗?',QMessageBox.Yes | QMessageBox.No,QMessageBox.No) if reply == QMessageBox.Yes: print("退出程序...") sys.exit() else: print("取消退出程序。") except Exception as e: print(f"关闭采集失败: {e}") if __name__ == '__main__': app = QApplication(sys.argv) window = MyWindows() window.show() sys.exit(app.exec_())
最新发布
06-28
在 PyQt5 应用程序中,错误 `'int' object has no attribute 'text'` 通常表示代码尝试访问一个整数对象的 `text()` 方法。这通常发生在将整数值误赋给需要 QObject 或其子类(如 QLineEdit、QLabel 等)的变量时。 ### 常见原因及解决方案 1. **误将整数赋值给控件变量** 如果在初始化界面元素(如 `QLineEdit`、`QPushButton`)时,意外地将整数值赋给了原本应该引用控件的变量,则后续调用 `.text()` 方法时会引发此错误。 ```python self.lineEdit = 123 # 错误:覆盖了QLineEdit实例 text = self.lineEdit.text() # 此时self.lineEdit是int类型,没有text方法 ``` 解决方案是确保控件变量始终指向正确的 QWidget 子类实例: ```python self.lineEdit = QtWidgets.QLineEdit(self) # 正确初始化 text = self.lineEdit.text() ``` 2. **信号与槽连接中的参数类型不匹配** PyQt5 的信号和槽机制允许传递任意类型的参数,但如果槽函数期望接收的是包含 `.text()` 方法的对象(如 `QLineEdit`),而实际发送的是整数,则会导致运行时错误[^3]。 示例: ```python def on_button_clicked(value): print(value.text()) # value 是 int 类型,不是预期的 QWidget 子类 button.clicked.connect(lambda: on_button_clicked(123)) # 错误传参 ``` 正确做法是确保信号传递的数据类型与槽函数处理的逻辑一致: ```python line_edit = QtWidgets.QLineEdit() button.clicked.connect(lambda: on_button_clicked(line_edit)) ``` 3. **多线程操作中数据传递问题** 在使用 `QThread` 或 `PyQt5.QtCore.QRunnable` 实现多线程时,若通过信号传递了整数而非预期的字符串或控件对象,也可能导致此类错误[^1]。 示例: ```python class Worker(QObject): finished = pyqtSignal(int) def run(self): result = 42 self.finished.emit(result) # 发送整数而非字符串或控件 def handle_finished(data): print(data.text()) # data 是 int 类型,无法调用 .text() worker = Worker() worker.finished.connect(handle_finished) ``` 修正方式为确保信号传递的数据结构符合预期: ```python class Worker(QObject): finished = pyqtSignal(str) def run(self): result = "Success" self.finished.emit(result) ``` 4. **动态生成控件时未正确绑定引用** 当根据某些条件动态创建控件并将其添加到布局中时,如果未能正确保存对这些控件的引用,可能会导致后续访问时出现类型错误。 示例: ```python for i in range(5): btn = QPushButton(f"Button {i}") btn.clicked.connect(lambda _, idx=i: self.handle_click(idx)) layout.addWidget(btn) def handle_click(self, index): sender = self.sender() print(index.text()) # index 是 int 类型,不是 QPushButton 实例 ``` 改进方案是在槽函数中直接使用 `sender()` 获取触发事件的控件: ```python def handle_click(self): button = self.sender() print(button.text()) ``` --- ### 总结 错误 `'int' object has no attribute 'text'` 根源于试图访问非字符串或非控件对象的 `.text()` 方法。要避免此类问题,开发者应: - 确保所有 UI 控件变量始终指向有效的 `QWidget` 子类实例; - 在信号与槽通信中保持参数类型一致性; - 多线程环境下谨慎处理跨线程数据交换; - 动态创建控件时妥善管理其生命周期和引用关系。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值