首页 > 解决方案 > 转换遍历行的函数以应用方法 pandas

问题描述

我有一个函数,我在数据帧的行上一个接一个地运行。我想以某种方式将其转换为 pandas apply 方法或类似方法,并希望能够提高性能。

所以数据框看起来像这样:

df
       object_id  ...                        param_dict
8804       15563  ...                         {81: 2.0}
8805       15566  ...                         {81: 2.0}
8806       15553  ...                         {81: 2.0}
8808       15531  ...                         {81: 2.0}
8811       15639  ...                         {81: 2.0}
...          ...  ...                               ...
16525       1158  ...  {4: 9963.302345992126, 46: 92.4}
16526       1156  ...               {4: -0.0, 46: 67.5}
16527       1089  ...                 {4: -0.0, 46: 76}
16528        898  ...               {4: -0.0, 46: 67.5}
16531        893  ...               {4: -0.0, 46: 67.5}
[1333 rows x 8 columns]

和功能:

def function(df):
    # running over the index of the dataframe
    for index in df.index:

        # running over the keys of the dataframe['param_dict'] dictionaries
        for key in df['param_dict'][index]:
            if df['param_dict'][index][key] == 0:
                continue

            if key in [4, 27]:
                print(df['name'][index], df['param_dict'][index][key], 1)

            elif key in [46, 28, 29]:
                print(df['name'][index], df['param_dict'][index][key], 2)

            else:
                print(df['name'][index], df['param_dict'][index][key], 3)

    return None

所以目前,第一个 for 循环运行了 1333 次,并且根据字典的键,内部 for 循环也运行了几次。有没有办法以某种方式将此函数转换为应用方法,这样至少我不需要遍历索引?

这是简单的数据集:

df = pd.DataFrame({'name': ['a', 'b', 'c'], 'param_dict': [{4: 0, 1: 4}, {46: True}, {35: False, 25: 0}]})
    

标签: pythonpandasdataframefor-loopapply

解决方案


您可以创建一个应用于 pandas 数据帧中每一行的函数,修改该行并将其新版本返回给 df,例如:

def func(row):
  row['key1'] = row['key1'] + row['key2']
  return row

然后你可以将它应用到索引上:

df = df.apply(func, axis=1)

推荐阅读