下载安卓APP箭头
箭头给我发消息

客服QQ:3315713922

Pandas处理大数据的性能优化技巧

作者:匿名     来源: 大数据点击数:574发布时间: 2023-01-03 22:24:49

标签: 数据分析工具Pandas

  Pandas是Python中最著名的数据分析工具。在处理数据集时,每个人都会使用到它。但是随着数据大小的增加,执行某些操作的某些方法会比其他方法花费更长的时间。

  Pandas是Python中最著名的数据分析工具。在处理数据集时,每个人都会使用到它。但是随着数据大小的增加,执行某些操作的某些方法会比其他方法花费更长的时间。所以了解和使用更快的方法非常重要,特别是在大型数据集中,本文将介绍一些使用Pandas处理大数据时的技巧,希望对你有所帮助。

  数据生成

  为了方便介绍,我们生成一些数据作为演示,faker是一个生成假数据的Python包。这里我们直接使用它。

  复制

  1.  import random

  2.  from faker import Faker

      3.

  4.  fake = Faker()

      5.

  6.  car_brands = ["Audi","Bmw","Jaguar","Fiat","Mercedes","Nissan","Porsche","Toyota", None]

  7.  tv_brands = ["Beko", "Lg", "Panasonic", "Samsung", "Sony"]

      8.

  9.  def generate_record():

  10.  """ generates a fake row

  11.  """

  12.  cid = fake.bothify(text='CID-###')

  13.  name = fake.name()

  14.  age=fake.random_number(digits=2)

  15.  city = fake.city()

  16.  plate = fake.license_plate()

  17.  job = fake.job()

  18.  company = fake.company()

  19.  employed = fake.boolean(chance_of_getting_true=75)

  20.  social_security = fake.boolean(chance_of_getting_true=90)

  21.  healthcare = fake.boolean(chance_of_getting_true=95)

  22.  iban = fake.iban()

  23.  salary = fake.random_int(min=0, max=99999)

  24.  car = random.choice(car_brands)

  25.  tv = random.choice(tv_brands)

  26.  record = [cid, name, age, city, plate, job, company, employed,

  27.  social_security, healthcare, iban, salary, car, tv]

  28.  return record

      29.

      30. 

  31.  record = generate_record()

  32.  print(record)

      33.

  34.  """

  35.  ['CID-753', 'Kristy Terry', 5877566, 'North Jessicaborough', '988 XEE',

  36.  'Engineer, control and instrumentation', 'Braun, Robinson and Shaw',

  37.  True, True, True, 'GB57VOOS96765461230455', 27109, 'Bmw', 'Beko']

  38.   """

  我们创建了一个100万行的DF。

  复制

  1.  import os

  2.  import pandas as pd

  3.  from multiprocessing import Pool

      4.

  5.  N= 1_000_000

      6.

  7.  if __name__ == '__main__':

  8.  cpus = os.cpu_count()

  9.  pool = Pool(cpus-1)

  10.  async_results = []

  11.  for _ in range(N):

  12.  async_results.append(pool.apply_async(generate_record))

  13.  pool.close()

  14.  pool.join()

  15.  data = []

  16.  for i, async_result in enumerate(async_results):

  17.  data.append(async_result.get())

  18.  df = pd.DataFrame(data=data, columns=["CID", "Name", "Age", "City", "Plate", "Job", "Company",

  19.  "Employed", "Social_Security", "Healthcare", "Iban",

  20.  "Salary", "Car", "Tv"])

  磁盘IO

  Pandas可以使用不同的格式保存DF。让我们比较一下这些格式的速度。

  复制

  1.  #Write

      2.

  3.  %timeit df.to_csv("df.csv")

  4.  #3.77 s ± 339 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      5.

  6.  %timeit df.to_pickle("df.pickle")

  7.  #948 ms ± 13.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      8.

  9.  %timeit df.to_parquet("df")

  10.  #2.77 s ± 13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      11.

  12.  %timeit df.to_feather("df.feather")

  13.  #368 ms ± 19.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      14.

  15.  def write_table(df):

  16.  dtf = dt.Frame(df)

  17.  dtf.to_csv("df_.csv")

      18.

  19.  %timeit write_table(df)

  20.  #559 ms ± 10.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

  复制

  1.  #Read

      2.

  3.  %timeit df=pd.read_csv("df.csv")

  4.  #1.89 s ± 22.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      5.

  6.  %timeit df=pd.read_pickle("df.pickle")

  7.  #402 ms ± 6.96 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      8.

  9.  %timeit df=pd.read_parquet("df")

  10.  #480 ms ± 3.62 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      11.

  12.  %timeit df=pd.read_feather("df.feather")

  13.  #754 ms ± 8.31 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      14.

  15.  def read_table():

  16.  dtf = dt.fread("df.csv")

  17.  df = dtf.to_pandas()

  18.  return df

      19.

  20.  %timeit df = read_table()

  21.  #869 ms ± 29.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

  CSV格式是运行最慢的格式。在这个比较中,我有包含Excel格式(read_excel),因为它更慢,并且还要安装额外的包。

  在使用CSV进行的操作中,首先建议使用datatable库将pandas转换为datatable对象,并在该对象上执行读写操作这样可以得到更快的结果。

  但是如果数据可控的话建议直接使用pickle 。

  数据类型

  在大型数据集中,我们可以通过强制转换数据类型来优化内存使用。

  例如,通过检查数值特征的最大值和最小值,我们可以将数据类型从int64降级为int8,它占用的内存会减少8倍。

  复制

  1.  df.info()

      2.

  3.  """

  4.  <class 'pandas.core.frame.DataFrame'>

  5.  RangeIndex: 1000000 entries, 0 to 999999

  6.  Data columns (total 14 columns):

  7.  # Column Non-Null Count Dtype

  8.  --- ------ -------------- -----

  9.  0 CID 1000000 non-null object

  10.  1 Name 1000000 non-null object

  11.  2 Age 1000000 non-null int64

  12.  3 City 1000000 non-null object

  13.  4 Plate 1000000 non-null object

  14.  5 Job 1000000 non-null object

  15.  6 Company 1000000 non-null object

  16.  7 Employed 1000000 non-null bool

  17.  8 Social_Security 1000000 non-null bool

  18.  9 Healthcare 1000000 non-null bool

  19.  19.  10 Iban 1000000 non-null object

  20.  11 Salary 1000000 non-null int64

  21.  12 Car 888554 non-null object

  22.  13 Tv 1000000 non-null object

  23.  dtypes: bool(3), int64(2), object(9)

  24.  memory usage: 86.8+ MB

  25.  """

  我们根据特征的数值范围对其进行相应的转换,例如AGE特征的范围在0到99之间,可以将其数据类型转换为int8。

  复制

  1.  #int

      2.

  3.  df["Age"].memory_usage(index=False, deep=False)

  4.  #8000000

      5.

  6.  #convert

  7.  df["Age"] = df["Age"].astype('int8')

      8.

  9.  df["Age"].memory_usage(index=False, deep=False)

  10.  #1000000

      11.

  12.  #float

      13.

  14.  df["Salary_After_Tax"] = df["Salary"] * 0.6

  15.  df["Salary_After_Tax"].memory_usage(index=False, deep=False)

  16.  #8000000

  17.  df["Salary_After_Tax"] = df["Salary_After_Tax"].astype('float16')

  18.  df["Salary_After_Tax"].memory_usage(index=False, deep=False)

  19.  #2000000

      20.

  21.  #categorical

  22.  df["Car"].memory_usage(index=False, deep=False)

  23.  #8000000

      24.

  25.  df["Car"] = df["Car"].astype('category')

      26.

  27.  df["Car"].memory_usage(index=False, deep=False)

  28.  #1000364

  或者在文件读取过程中直接指定数据类型。

  复制

  1.  dtypes = {

  2.  'CID' : 'int32',

  3.  'Name' : 'object',

  4.  'Age' : 'int8',

  5.  ...

  6.  }

  7.  dates=["Date Columns Here"]

      8.

  9.  df = pd.read_csv(dtype=dtypes, parse_dates=dates)

  查询过滤

  常规过滤方法:

  复制

  1.  %timeit df_filtered = df[df["Car"] == "Mercedes"]

  2.  #61.8 ms ± 2.55 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

  对于分类特征,我们可以使用pandas的group_by和get_group方法。

  复制

  1.  %timeit df.groupby("Car").get_group("Mercedes")

  2.  #92.1 ms ± 4.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

      3.

  4.  df_grouped = df.groupby("Car")

  5.  %timeit df_grouped.get_group("Mercedes")

  6.  #14.8 ms ± 167 µs per loop (mean ± std. dev. of 7 runs, 1 loop each)

  分组的操作比正常应用程序花费的时间要长。如果要对分类特征进行很多过滤操作,例如在本例中,如果我们从头进行分组,并且只看get_group部分的执行时间,我们将看到该过程实际上比常规方法更快。也就是说,对于重复的过滤操作,我们可以首选此方法(get_group)。

  计数

  Value_counts方法比groupby和following size方法更快。

  复制

  1.  %timeit df["Car"].value_counts()

  2.  #49.1 ms ± 378 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

  3.  """

  4.  Toyota 111601

  5.  Porsche 111504

  6.  Jaguar 111313

  7.  Fiat 111239

  8.  Nissan 110960

  9.  Bmw 110906

  10.  Audi 110642

  11.  Mercedes 110389

  12.  Name: Car, dtype: int64

  13.  """

      14.

  15.  %timeit df.groupby("Car").size()

  16.  #64.5 ms ± 37.9 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

  17.  """

  18.  Car

  19.  Audi 110642

  20.  Bmw 110906

  21.  Fiat 111239

  22.  Jaguar 111313

  23.  Mercedes 110389

  24.  Nissan 110960

  25.  Porsche 111504

  26.  Toyota 111601

  27.  dtype: int64

  28.   """

  迭代

  在大容量数据集上迭代需要很长时间。所以有必要在这方面选择最快的方法。我们可以使用Pandas的iterrows和itertuples方法,让我们将它们与常规的for循环实现进行比较。

  复制

  1.  def foo_loop(df):

  2.  total = 0

  3.  for i in range(len(df)):

  4.  total += df.iloc[i]['Salary']

  5.  return total

      6.

  7.  %timeit foo_loop(df)

  8.  #34.6 s ± 593 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      9.

  10.  def foo_iterrows(df):

  11.  total = 0

  12.  for index, row in df.iterrows():

  13.  total += row['Salary']

  14.  return total

      15.

  16.  %timeit foo_iterrows(df)

  17.  #22.7 s ± 761 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      18.

  19.  def foo_itertuples(df):

  20.  total = 0

  21.  for row in df.itertuples():

  22.  total += row[12]

  23.  return total

      24.

  25.  %timeit foo_itertuples(df)

  26.  #1.22 s ± 14.8 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

  Iterrows方法比for循环更快,但itertuples方法是最快的。

  另外就是Apply方法允许我们对DF中的序列执行任何函数。

  复制

  1.  def foo(val):

  2.  if val > 50000:

  3.  return "High"

  4.  elif val <= 50000 and val > 10000:

  5.  return "Mid Level"

  6.  else:

  7.  return "Low"

      8.

  9.  df["Salary_Category"] = df["Salary"].apply(foo)

  10.  print(df["Salary_Category"])

  11.  """

  12.  0 High

  13.  1 High

  14.  2 Mid Level

  15.  3 High

  16.  4 Low

  17.  ...

  18.  999995 High

  19.  999996 Low

  20.  999997 High

  21.  999998 High

  22.  999999 Mid Level

  23.  Name: Salary_Category, Length: 1000000, dtype: object

  24.  """

      25.

  26.  %timeit df["Salary_Category"] = df["Salary"].apply(foo)

  27.  #112 ms ± 50.6 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

      28.

  29.  def boo():

  30.  liste = []

  31.  for i in range(len(df)):

  32.  val = foo(df.loc[i,"Salary"])

  33.  liste.append(val)

  34.  df["Salary_Category"] = liste

      35.

  36.  %timeit boo()

  37.  #5.73 s ± 130 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

  而map方法允许我们根据给定的函数替换一个Series中的每个值。

  复制

  1.  print(df["Salary_Category"].map({'High': "H", "Mid Level": "M", "Low": "L"}))

  2.  """

  3.  0 H

  4.  1 H

  5.  2 M

  6.  3 H

  7.  4 L

  8.  ..

  9.  999995 H

  10.  999996 L

  11.  999997 H

  12.  999998 H

  13.  999999 M

  14.  Name: Salary_Category, Length: 1000000, dtype: object

  15.  """

      16.

  17.  print(df["Salary_Category"].map("Salary Category is {}".format))

  18.  """

  19.  0 Salary Category is High

  20.  1 Salary Category is High

  21.  2 Salary Category is Mid Level

  22.  3 Salary Category is High

  23.  4 Salary Category is Low

  24.  ...

  25.  999995 Salary Category is High

  26.  999996 Salary Category is Low

  27.  999997 Salary Category is High

  28.  999998 Salary Category is High

  29.  999999 Salary Category is Mid Level

  30.  Name: Salary_Category, Length: 1000000, dtype: object

  31.  """

      32.

  33.  df["Salary_Category"] = df["Salary"].map(foo)

  34.  print(df["Salary_Category"])

  35.  """

  36.  0 High

  37.  1 High

  38.  2 Mid Level

  39.  3 High

  40.  4 Low

  41.  ...

  42.  999995 High

  43.  999996 Low

  44.  999997 High

  45.  999998 High

  46.  999999 Mid Level

  47.  Name: Salary_Category, Length: 1000000, dtype: object

  让我们比较一下标对salary 列进行标准化工时每一中迭代方法的时间吧。

  复制

  1.  min_salary = df["Salary"].min()

  2.  max_salary = df["Salary"].max()

      3.

  4.  def normalize_for_loc(df, min_salary, max_salary):

  5.  normalized_salary = np.zeros(len(df, ))

  6.  for i in range(df.shape[0]):

  7.  normalized_salary[i] = (df.loc[i, "Salary"] - min_salary) / (max_salary - min_salary)

  8.  df["Normalized_Salary"] = normalized_salary

  9.  return df

      10.

  11.  %timeit normalize_for_loc(df, min_salary, max_salary)

  12.  #5.45 s ± 15.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      13.

  14.  def normalize_for_iloc(df, min_salary, max_salary):

  15.  normalized_salary = np.zeros(len(df, ))

  16.  for i in range(df.shape[0]):

  17.  normalized_salary[i] = (df.iloc[i, 11] - min_salary) / (max_salary - min_salary)

  18.  df["Normalized_Salary"] = normalized_salary

  19.  return df

      20. 

  21.  %timeit normalize_for_iloc(df, min_salary, max_salary)

  22.  #13.8 s ± 29.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      23.

  24.  def normalize_for_iloc(df, min_salary, max_salary):

  25.  normalized_salary = np.zeros(len(df, ))

  26.  for i in range(df.shape[0]):

  27.  normalized_salary[i] = (df.iloc[i]["Salary"] - min_salary) / (max_salary - min_salary)

  28.  df["Normalized_Salary"] = normalized_salary

  29.  return df

      30.

  31.  %timeit normalize_for_iloc(df, min_salary, max_salary)

  32.  #34.8 s ± 108 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      33.

  34.  def normalize_for_iterrows(df, min_salary, max_salary):

  35.  normalized_salary = np.zeros(len(df, ))

  36.  i = 0

  37.  for index, row in df.iterrows():

  38.  normalized_salary[i] = (row["Salary"] - min_salary) / (max_salary - min_salary)

  39.  i += 1

  40.  df["Normalized_Salary"] = normalized_salary

  41.  return df

      42.

  43.  %timeit normalize_for_iterrows(df, min_salary, max_salary)

  44.  #21.7 s ± 53.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      45.

  46.  def normalize_for_itertuples(df, min_salary, max_salary):

  47.  normalized_salary = list()

  48.  for row in df.itertuples():

  49.  normalized_salary.append((row[12] - min_salary) / (max_salary - min_salary))

  50.  df["Normalized_Salary"] = normalized_salary

  51.  return df

      52.

  53.  %timeit normalize_for_itertuples(df, min_salary, max_salary)

  54.  #1.34 s ± 4.29 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      55.

  56.  def normalize_map(df, min_salary, max_salary):

  57.  df["Normalized_Salary"] = df["Salary"].map(lambda x: (x - min_salary) / (max_salary - min_salary))

  58.  return df

      59.

  60.  %timeit normalize_map(df, min_salary, max_salary)

  61.  #178 ms ± 970 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

      62.

  63.  def normalize_apply(df, min_salary, max_salary):

  64.  df["Normalized_Salary"] = df["Salary"].apply(lambda x: (x - min_salary) / (max_salary - min_salary))

  65.  return df

  66.  %timeit normalize_apply(df, min_salary, max_salary)

  67.  #182 ms ± 1.83 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

      68.

  69.  def normalize_vectorization(df, min_salary, max_salary):

  70.  df["Normalized_Salary"] = (df["Salary"] - min_salary) / (max_salary - min_salary)

  71.  return df

      72.

  73.  %timeit normalize_vectorization(df, min_salary, max_salary)

  74.  #1.58 ms ± 7.87 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)

  可以看到:

  loc比iloc快。

  如果你要使用iloc,那么最好使用这样df.iloc[i, 11]的格式。

  Itertuples比loc更好,iterrows确差不多。

  Map和apply是第二种更快的选择。

  向量化的操作是最快的。

  向量化

  向量化操作需要定义一个向量化函数,该函数接受嵌套的对象序列或numpy数组作为输入,并返回单个numpy数组或numpy数组的元组。

  复制

  1.  def foo(val, min_salary, max_salary):

  2.  return (val - min_salary) / (max_salary - min_salary)

      3.

  4.  foo_vectorized = np.vectorize(foo)

  5.  %timeit df["Normalized_Salary"] = foo_vectorized(df["Salary"], min_salary, max_salary)

  6.  #154 ms ± 310 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

      7.

      8.

  9.  #conditional

  10.  %timeit df["Old"] = (df["Age"] > 80)

  11.  #140 µs ± 11.8 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

      12.

  13.  #isin

  14.  %timeit df["Old"] = df["Age"].isin(range(80,100))

  15.  #17.4 ms ± 466 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

      16.

  17.  #bins with digitize

  18.  %timeit df["Age_Bins"] = np.digitize(df["Age"].values, bins=[0, 18, 36, 54, 72, 100])

  19.  #12 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

  20.  print(df["Age_Bins"])

  21.  """

  22.  0 3

  23.  1 5

  24.  2 4

  25.  3 3

  26.  4 5

  27.  ..

  28.  999995 4

  29.  999996 2

  30.  999997 3

  31.  999998 1

  32.  999999 1

  33.  Name: Age_Bins, Length: 1000000, dtype: int64

  34.  """

  索引

  使用.at方法比使用.loc方法更快。

  复制

  1.  %timeit df.loc[987987, "Name"]

  2.  #5.05 µs ± 33.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

      3.

  4.  %timeit df.at[987987, "Name"]

  5.  #2.39 µs ± 23.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

  Swifter

  Swifter是一个Python包,它可以比常规的apply方法更有效地将任何函数应用到DF。

  复制

  1.  !pip install swifter

  2.  import swifter

      3.

  4.  #apply

  5.  %timeit df["Normalized_Salary"] = df["Salary"].apply(lambda x: (x - min_salary) / (max_salary - min_salary))

  6.  #192 ms ± 9.08 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

      7.

  8.  #swifter.apply

  9.  %timeit df["Normalized_Salary"] = df["Salary"].swifter.apply(lambda x: (x - min_salary) / (max_salary - min_salary))

  10.  #83.5 ms ± 478 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

  总结

  如果可以使用向量化,那么任何操作都应该优先使用它。对于迭代操作可以优先使用itertuples、apply或map等方法。还有一些单独的Python包,如dask、vaex、koalas等,它们都是构建在pandas之上或承担类似的功能,也可以进行尝试。

  来源: DeepHub IMBA

    >>>>>>点击进入大数据专题

赞(13)
踩(0)
分享到:
华为认证网络工程师 HCIE直播课视频教程