pandas 通过创建函数来创建标记并检查panda Dataframe 中的列值

3pvhb19x  于 2023-01-19  发布在  其他
关注(0)|答案(2)|浏览(133)

我有从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

请帮帮我。

eqqqjvef

eqqqjvef1#

在循环中使用range时,必须使用.iloc来获取行。但是,可以对函数进行矢量化,以避免使用np.select进行循环:

def checkFlags_current(var):
    conds = [(var > 0) & (var.diff().abs() > 30), var.isna(), var == 0]
    choices = [1, 3, 2]
    return np.select(condlist=conds, choicelist=choices, default=0)

tmd_flags['Load Current(A)'] = checkFlags_current(tmd.iloc[:, 10])
sauutmhj

sauutmhj2#

使用numpy.select代替循环,也分配给相同的 Dataframe tmd

def checkFlags_current(x):
    """
        This function calculates,

            Input(s):
            - x: Current in Ampere

            Returns:
            - flags
    """
    flags = np.select([x.isna(), x.eq(0), x.gt(0) & x.diff().abs().gt(30)],
                      [3,2,1], 0)
    return flags

tmd['Load Current(A)'] = checkFlags_current(tmd.iloc[:, 10])

相关问题