import numpy as np import pandas as pd import xlrd import os import matplotlib.pyplot as plt def get_all_fill_paths(dir_path): file_paths = [] for root, _, files in os.walk(dir_path): for file in files: file_paths.append(os.path.join(root, file)) return file_paths dir_path = r'C:\Users\lxz15\Desktop\电流数据2' file_paths = get_all_fill_paths(dir_path) data = pd.DataFrame() # 定义一个空的 DataFrame all_a = [] for i, file_path in enumerate(file_paths): df = pd.read_excel(file_path) for j in range(0, 1): for k in range(0, 1): a = pd.DataFrame(df.iloc[2 + 3 * k:5 + 3 * k, 7 + j].values) # 将列表转换为 DataFrame data = pd.concat([data, a], axis=1) # 将 a 添加到 data 中 all_a.append(a) all_a = np.array(all_a) print(all_a) all_a = np.where(np.char.isdigit(all_a.astype(float)), all_a, np.nan) all_a = all_a.astype(float) all_a_avg = np.nanmean(all_a, axis=(0, 1)) print(all_a_avg) # 计算平均数 diff = all_a - all_a_avg print(diff) # 计算差 diff_sum = np.nansum(np.square(diff)) print(diff_sum) # 计算差的平方和 diff_sqrt = np.sqrt(diff_sum) # 计算平方根 print(diff_sqrt)怎么改
时间: 2024-02-13 14:04:57 浏览: 112
python 3.74 运行import numpy as np 报错lib\site-packages\numpy\__init__.py
根据错误信息 `TypeError: string operation on non-string array`,可以确定问题出现在 `all_a = np.where(np.char.isdigit(all_a.astype(float)), all_a, np.nan)` 这一行代码上,因为 `np.char.isdigit()` 用于检查字符串是否只包含数字字符。但是 `all_a` 可能不是字符串类型的数组,所以不能直接进行字符串操作。
可以通过以下代码修改,先将 `all_a` 转换为字符串类型的数组,再进行字符串操作:
```
all_a = np.array(all_a, dtype=str) # 转换为字符串类型的数组
all_a = np.where(np.char.isdigit(all_a), all_a, np.nan) # 对字符串类型的数组进行字符串操作
all_a = all_a.astype(float) # 转换为浮点数类型的数组
```
这样就可以避免该错误了。
阅读全文