应用行特定条件的有效方法

时间:2019-09-30 08:29:16

标签: python pandas

我有关于出境航班的数据,包括日期,月份,机场等信息。 我想遍历各行,并为每行计算从同一机场出发的15m以内的航班数。 我的代码似乎可以运行,但是非常慢(在10万行中,需要约一个小时才能运行)。 有没有办法提高效率? 这是一个示例文件link 谢谢!

[Key]

1 个答案:

答案 0 :(得分:1)

您的代码

import pandas as pd

cols = ['Month', 'DayofMonth', 'DayOfWeek', 'DepTime', 'UniqueCarrier', 'Origin', 'Dest', 'Distance']
data = [
  ['c-8', 'c-21', 'c-7', 1934, 'AA', 'ATL', 'DFW', 732],
  ['c-6', 'c-19', 'c-2', 1942, 'AA', 'ATL', 'CLE', 999],
  ['c-6', 'c-19', 'c-2', 1955, 'AA', 'ATL', 'CLE', 111],
  ['c-4', 'c-20', 'c-3', 1548, 'US', 'PIT', 'MCO', 834],
  ['c-9', 'c-2', 'c-5', 1422, 'XE', 'RDU', 'CLE', 416],
  ['c-11', 'c-25', 'c-6', 1015, 'OO', 'DEN', 'MEM', 872],
  ['c-10', 'c-7', 'c-6', 1828, 'WN', 'MDW', 'OMA', 423]
]

df = pd.DataFrame(data=data, columns=cols)
df['close_out15'] = 0

def algo_v1(df):


time_allowance = 15
  close_out = []
  i=0
  for index, row in df.iterrows():
      i+=1

      idf = df.loc[(df['Origin'] == row['Origin']) &
                  (df['Month'] == row['Month']) &
                  (df['DayofMonth'] == row['DayofMonth']) &
                  (df['DepTime'] < row['DepTime'] + time_allowance) &
                  (df['DepTime'] > row['DepTime'] - time_allowance), :]

      close_out.append(len(idf))   

  col_name = 'close_out' + str(time_allowance)
  df[col_name] = close_out

  return df

测试:

#print(algo_v1(df))
#%timeit algo_v1(df)

      Month DayofMonth DayOfWeek  DepTime  ... Origin Dest Distance  close_out15
0   c-8       c-21       c-7     1934  ...    ATL  DFW      732            1
1   c-6       c-19       c-2     1942  ...    ATL  CLE      999            2
2   c-6       c-19       c-2     1955  ...    ATL  CLE      111            2
3   c-4       c-20       c-3     1548  ...    PIT  MCO      834            1
4   c-9        c-2       c-5     1422  ...    RDU  CLE      416            1
5  c-11       c-25       c-6     1015  ...    DEN  MEM      872            1
6  c-10        c-7       c-6     1828  ...    MDW  OMA      423            1

[7 rows x 9 columns]
10 loops, best of 3: 28.4 ms per loop

仅使用groupbyapply方法就可以进行一些基本的改进。

def filter_and_count(df):
  time_threshold = 15

  for idx, row in df.iterrows():
    row['close_out15'] = df['UniqueCarrier'].loc[
      (df['DepTime'] <= row['DepTime'] + time_threshold)
      & (df['DepTime'] >= row['DepTime'] - time_threshold)
    ].count()


def algo_v2(df):
  df.groupby(['Origin', 'Month', 'DayofMonth']).apply(filter_and_count)

  return df

测试性能

#print(algo_v2(df))
#%timeit algo_v2(df)

  Month DayofMonth DayOfWeek  DepTime  ... Origin Dest Distance  close_out15
0   c-8       c-21       c-7     1934  ...    ATL  DFW      732            1
1   c-6       c-19       c-2     1942  ...    ATL  CLE      999            2
2   c-6       c-19       c-2     1955  ...    ATL  CLE      111            2
3   c-4       c-20       c-3     1548  ...    PIT  MCO      834            1
4   c-9        c-2       c-5     1422  ...    RDU  CLE      416            1
5  c-11       c-25       c-6     1015  ...    DEN  MEM      872            1
6  c-10        c-7       c-6     1828  ...    MDW  OMA      423            1

[7 rows x 9 columns]
100 loops, best of 3: 18.8 ms per loop

仅按某些字段进行分组,就可以注意到大约提高了34%

下一步要提高性能

有两个主要选项:

  • 继续提高算法的性能
  • 并行化

请注意,这两个选项也可能一起工作。

提高性能

使用NumbaCtyhon可能是good options

并行化

Multiprocessing module是替代方法。其他更高级的抽象选项是this one