我有从excel文件中读取的Pandas数据框,我需要检查这些列中的值是否符合某些条件。首先,我写了下面的代码,它工作得很好。
tmd.iloc[:, 10] = tmd.iloc[:, 10].fillna(tmd.iloc[:, 10].mean())
tmd.iloc[tmd.iloc[:, 10] == 0, 10] = tmd.iloc[:, 10].mean()
tmd.iloc[:, 10] = tmd.iloc[:, 10].where(~((tmd.iloc[:, 10] > 0) & (pd.Series.abs(tmd.iloc[:, 10].diff()) > 30)), tmd.iloc[:, 10].mean())
然而,这个操作所需的行数在增加,所以我写了一个函数,并尝试将它应用到 Dataframe 的每一列。
def checkFlags_current(var):
"""
This function calculates,
Input(s):
- var1: Current in Ampere
Returns:
- flags
"""
rows = len(var)
flags = np.zeros((rows, 1))
for i in range(0, rows):
if (var[i] > 0 & (abs(var[i+1] - var[i]) > 30)):
flags[i] = 1
elif (pd.isnull(var[i])):
flags[i] = 3
elif (var[i] == 0):
flags[i] = 2
else:
flags[i] = 0
flags = list(itertools.chain(*flags))
return flags
tmd_flags['Load Current(A)'] = checkFlags_current(tmd.iloc[:, 10])
但是,我得到了KeyError。
File "D:\AssetManager\Scripts\req_functions.py", line 1215, in checkFlags_current
if (var[i] > 0 & (abs(var[i+1] - var[i]) > 30)):
File "C:\Users\jadha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\core\series.py", line 958, in __getitem__
return self._get_value(key)
File "C:\Users\jadha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\core\series.py", line 1069, in _get_value
loc = self.index.get_loc(label)
File "C:\Users\jadha\AppData\Local\Packages\PythonSoftwareFoundation.Python.3.9_qbz5n2kfra8p0\LocalCache\local-packages\Python39\site-packages\pandas\core\indexes\range.py", line 387, in get_loc
raise KeyError(key) from err
KeyError: 32073
请帮帮我。
2条答案
按热度按时间eqqqjvef1#
在循环中使用
range
时,必须使用.iloc
来获取行。但是,可以对函数进行矢量化,以避免使用np.select
进行循环:sauutmhj2#
使用
numpy.select
代替循环,也分配给相同的 Dataframetmd
: