关于机器学习:Pandas处理大数据的性能优化技巧

37次阅读

共计 11391 个字符,预计需要花费 29 分钟才能阅读完成。

Pandas 是 Python 中最驰名的数据分析工具。在解决数据集时,每个人都会应用到它。然而随着数据大小的减少,执行某些操作的某些办法会比其余办法破费更长的工夫。所以理解和应用更快的办法十分重要,特地是在大型数据集中,本文将介绍一些应用 Pandas 解决大数据时的技巧,心愿对你有所帮忙

数据生成

为了不便介绍,咱们生成一些数据作为演示,faker 是一个生成假数据的 Python 包。这里咱们间接应用它

 import random
 from faker import Faker
 
 fake = Faker()
 
 car_brands = ["Audi","Bmw","Jaguar","Fiat","Mercedes","Nissan","Porsche","Toyota", None]
 tv_brands = ["Beko", "Lg", "Panasonic", "Samsung", "Sony"]
 
 def generate_record():
     """generates a fake row"""
     cid = fake.bothify(text='CID-###')
     name = fake.name()
     age=fake.random_number(digits=2) 
     city = fake.city()
     plate = fake.license_plate()
     job = fake.job()
     company = fake.company()
     employed = fake.boolean(chance_of_getting_true=75)
     social_security = fake.boolean(chance_of_getting_true=90)
     healthcare = fake.boolean(chance_of_getting_true=95)
     iban = fake.iban()
     salary = fake.random_int(min=0, max=99999)
     car = random.choice(car_brands)
     tv = random.choice(tv_brands)
     record = [cid, name, age, city, plate, job, company, employed, 
               social_security, healthcare, iban, salary, car, tv]
     return record
     
     
 record = generate_record()
 print(record)
 
 """['CID-753','Kristy Terry', 5877566,'North Jessicaborough','988 XEE','Engineer, control and instrumentation','Braun, Robinson and Shaw', 
 True, True, True, 'GB57VOOS96765461230455', 27109, 'Bmw', 'Beko']
 """

咱们创立了一个 100 万行的 DF。

 import os
 import pandas as pd
 from multiprocessing import Pool
 
 N= 1_000_000
 
 if __name__ == '__main__':
     cpus = os.cpu_count()
     pool = Pool(cpus-1)
     async_results = []
     for _ in range(N):
         async_results.append(pool.apply_async(generate_record))
     pool.close()
     pool.join()
     data = []
     for i, async_result in enumerate(async_results):
         data.append(async_result.get())
     df = pd.DataFrame(data=data, columns=["CID", "Name", "Age", "City", "Plate", "Job", "Company",
                                      "Employed", "Social_Security", "Healthcare", "Iban", 
                                      "Salary", "Car", "Tv"])

磁盘 IO

Pandas 能够应用不同的格局保留 DF。让咱们比拟一下这些格局的速度。

 #Write
 
 %timeit df.to_csv("df.csv")
 #3.77 s ± 339 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
 
 %timeit df.to_pickle("df.pickle")
 #948 ms ± 13.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
 
 %timeit df.to_parquet("df")
 #2.77 s ± 13 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
 
 %timeit df.to_feather("df.feather")
 #368 ms ± 19.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
 
 def write_table(df):
     dtf = dt.Frame(df)
     dtf.to_csv("df_.csv")
 
 %timeit write_table(df)
 #559 ms ± 10.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

 #Read
 
 %timeit df=pd.read_csv("df.csv")
 #1.89 s ± 22.4 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
 
 %timeit df=pd.read_pickle("df.pickle")
 #402 ms ± 6.96 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
 
 %timeit df=pd.read_parquet("df")
 #480 ms ± 3.62 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
 
 %timeit df=pd.read_feather("df.feather")
 #754 ms ± 8.31 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)
 
 def read_table():
     dtf = dt.fread("df.csv")
     df = dtf.to_pandas()
     return df
 
 %timeit df = read_table()
 #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 倍。

 df.info()
 
 """<class'pandas.core.frame.DataFrame'>
 RangeIndex: 1000000 entries, 0 to 999999
 Data columns (total 14 columns):
  #   Column           Non-Null Count    Dtype 
 ---  ------           --------------    ----- 
  0   CID              1000000 non-null  object
  1   Name             1000000 non-null  object
  2   Age              1000000 non-null  int64 
  3   City             1000000 non-null  object
  4   Plate            1000000 non-null  object
  5   Job              1000000 non-null  object
  6   Company          1000000 non-null  object
  7   Employed         1000000 non-null  bool  
  8   Social_Security  1000000 non-null  bool  
  9   Healthcare       1000000 non-null  bool  
  10  Iban             1000000 non-null  object
  11  Salary           1000000 non-null  int64 
  12  Car              888554 non-null   object
  13  Tv               1000000 non-null  object
 dtypes: bool(3), int64(2), object(9)
 memory usage: 86.8+ MB
 """

咱们依据特色的数值范畴对其进行相应的转换,例如 AGE 特色的范畴在 0 到 99 之间,能够将其数据类型转换为 int8。

 #int
 
 df["Age"].memory_usage(index=False, deep=False)
 #8000000
 
 #convert
 df["Age"] = df["Age"].astype('int8')
 
 df["Age"].memory_usage(index=False, deep=False)
 #1000000
 
 #float
 
 df["Salary_After_Tax"] = df["Salary"] * 0.6
 df["Salary_After_Tax"].memory_usage(index=False, deep=False)
 #8000000
 df["Salary_After_Tax"] = df["Salary_After_Tax"].astype('float16')
 df["Salary_After_Tax"].memory_usage(index=False, deep=False)
 #2000000
 
 #categorical
 df["Car"].memory_usage(index=False, deep=False)
 #8000000
 
 df["Car"] = df["Car"].astype('category')
 
 df["Car"].memory_usage(index=False, deep=False)
 #1000364

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

 dtypes = {
     'CID' : 'int32',
     'Name' : 'object',
     'Age' : 'int8',
     ...
 }
 dates=["Date Columns Here"]
 
 df = pd.read_csv(dtype=dtypes, parse_dates=dates)

查问过滤

惯例过滤办法:

 %timeit df_filtered = df[df["Car"] == "Mercedes"]
 #61.8 ms ± 2.55 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

对于分类特色,咱们能够应用 pandas 的 group_by 和 get_group 办法。

%timeit df.groupby("Car").get_group("Mercedes")
#92.1 ms ± 4.38 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

df_grouped = df.groupby("Car")
%timeit df_grouped.get_group("Mercedes")
#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 办法更快。

%timeit df["Car"].value_counts()
#49.1 ms ± 378 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
"""
Toyota      111601
Porsche     111504
Jaguar      111313
Fiat        111239
Nissan      110960
Bmw         110906
Audi        110642
Mercedes    110389
Name: Car, dtype: int64
"""%timeit df.groupby("Car").size()
#64.5 ms ± 37.9 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
"""
Car
Audi        110642
Bmw         110906
Fiat        111239
Jaguar      111313
Mercedes    110389
Nissan      110960
Porsche     111504
Toyota      111601
dtype: int64
"""

迭代

在大容量数据集上迭代须要很长时间。所以有必要在这方面抉择最快的办法。咱们能够应用 Pandas 的 iterrows 和 itertuples 办法,让咱们将它们与惯例的 for 循环实现进行比拟。

def foo_loop(df):
    total = 0
    for i in range(len(df)):
        total += df.iloc[i]['Salary']
    return total

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

def foo_iterrows(df):
    total = 0
    for index, row in df.iterrows():
        total += row['Salary']
    return total

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

def foo_itertuples(df):
    total = 0
    for row in df.itertuples(): 
        total += row[12]
    return total

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

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

另外就是 Apply 办法容许咱们对 DF 中的序列执行任何函数。

def foo(val):
    if val > 50000:
        return "High"
    elif val <= 50000 and val > 10000:
        return "Mid Level"
    else:
        return "Low"

df["Salary_Category"] = df["Salary"].apply(foo)
print(df["Salary_Category"])
"""
0              High
1              High
2         Mid Level
3              High
4               Low
            ...    
999995         High
999996          Low
999997         High
999998         High
999999    Mid Level
Name: Salary_Category, Length: 1000000, dtype: object
"""%timeit df["Salary_Category"] = df["Salary"].apply(foo)
#112 ms ± 50.6 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

def boo():
    liste = []
    for i in range(len(df)):
        val = foo(df.loc[i,"Salary"])
        liste.append(val)
    df["Salary_Category"] = liste

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

而 map 办法容许咱们依据给定的函数替换一个 Series 中的每个值。

print(df["Salary_Category"].map({'High': "H", "Mid Level": "M", "Low": "L"}))
"""
0         H
1         H
2         M
3         H
4         L
         ..
999995    H
999996    L
999997    H
999998    H
999999    M
Name: Salary_Category, Length: 1000000, dtype: object
"""print(df["Salary_Category"].map("Salary Category is {}".format))"""
0              Salary Category is High
1              Salary Category is High
2         Salary Category is Mid Level
3              Salary Category is High
4               Salary Category is Low
                      ...             
999995         Salary Category is High
999996          Salary Category is Low
999997         Salary Category is High
999998         Salary Category is High
999999    Salary Category is Mid Level
Name: Salary_Category, Length: 1000000, dtype: object
"""df["Salary_Category"] = df["Salary"].map(foo)
print(df["Salary_Category"])
"""
0              High
1              High
2         Mid Level
3              High
4               Low
            ...    
999995         High
999996          Low
999997         High
999998         High
999999    Mid Level
Name: Salary_Category, Length: 1000000, dtype: object

让咱们比拟一下标对 salary 列进行规范化工时每一中迭代办法的工夫吧。

min_salary = df["Salary"].min()
max_salary = df["Salary"].max()

def normalize_for_loc(df, min_salary, max_salary):
    normalized_salary = np.zeros(len(df,))
    for i in range(df.shape[0]):
        normalized_salary[i] = (df.loc[i, "Salary"] - min_salary) / (max_salary - min_salary)
    df["Normalized_Salary"] = normalized_salary
    return df

%timeit normalize_for_loc(df, min_salary, max_salary)
#5.45 s ± 15.1 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

def normalize_for_iloc(df, min_salary, max_salary):
    normalized_salary = np.zeros(len(df,))
    for i in range(df.shape[0]):
        normalized_salary[i] = (df.iloc[i, 11] - min_salary) / (max_salary - min_salary)
    df["Normalized_Salary"] = normalized_salary
    return df

%timeit normalize_for_iloc(df, min_salary, max_salary)
#13.8 s ± 29.5 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

def normalize_for_iloc(df, min_salary, max_salary):
    normalized_salary = np.zeros(len(df,))
    for i in range(df.shape[0]):
        normalized_salary[i] = (df.iloc[i]["Salary"] - min_salary) / (max_salary - min_salary)
    df["Normalized_Salary"] = normalized_salary
    return df

%timeit normalize_for_iloc(df, min_salary, max_salary)
#34.8 s ± 108 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

def normalize_for_iterrows(df, min_salary, max_salary):
    normalized_salary = np.zeros(len(df,))
    i = 0
    for index, row in df.iterrows():
        normalized_salary[i] = (row["Salary"] - min_salary) / (max_salary - min_salary)
        i += 1
    df["Normalized_Salary"] = normalized_salary
    return df

%timeit normalize_for_iterrows(df, min_salary, max_salary)
#21.7 s ± 53.3 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

def normalize_for_itertuples(df, min_salary, max_salary):
    normalized_salary = list()
    for row in df.itertuples():
        normalized_salary.append((row[12] - min_salary) / (max_salary - min_salary))
    df["Normalized_Salary"] = normalized_salary
    return df

%timeit normalize_for_itertuples(df, min_salary, max_salary)
#1.34 s ± 4.29 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

def normalize_map(df, min_salary, max_salary):
    df["Normalized_Salary"] = df["Salary"].map(lambda x: (x - min_salary) / (max_salary - min_salary))
    return df

%timeit normalize_map(df, min_salary, max_salary)
#178 ms ± 970 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

def normalize_apply(df, min_salary, max_salary):
    df["Normalized_Salary"] = df["Salary"].apply(lambda x: (x - min_salary) / (max_salary - min_salary))
    return df
%timeit normalize_apply(df, min_salary, max_salary)
#182 ms ± 1.83 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

def normalize_vectorization(df, min_salary, max_salary):
    df["Normalized_Salary"] = (df["Salary"] - min_salary) / (max_salary - min_salary)
    return df

%timeit normalize_vectorization(df, min_salary, max_salary)
#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 数组的元组。

def foo(val, min_salary, max_salary):
    return (val - min_salary) / (max_salary - min_salary)

foo_vectorized = np.vectorize(foo)
%timeit df["Normalized_Salary"] = foo_vectorized(df["Salary"], min_salary, max_salary)
#154 ms ± 310 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

#conditional
%timeit df["Old"] = (df["Age"] > 80)
#140 µs ± 11.8 µs per loop (mean ± std. dev. of 7 runs, 10000 loops each)

#isin
%timeit df["Old"] = df["Age"].isin(range(80,100))
#17.4 ms ± 466 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

#bins with digitize
%timeit df["Age_Bins"] = np.digitize(df["Age"].values, bins=[0, 18, 36, 54, 72, 100])
#12 ms ± 107 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
print(df["Age_Bins"])
"""
0         3
1         5
2         4
3         3
4         5
         ..
999995    4
999996    2
999997    3
999998    1
999999    1
Name: Age_Bins, Length: 1000000, dtype: int64
"""

索引

应用.at 办法比应用.loc 办法更快。

%timeit df.loc[987987, "Name"]
#5.05 µs ± 33.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

%timeit df.at[987987, "Name"]
#2.39 µs ± 23.3 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)

Swifter

Swifter 是一个 Python 包,它能够比惯例的 apply 办法更无效地将任何函数利用到 DF。

!pip install swifter
import swifter

#apply
%timeit df["Normalized_Salary"] = df["Salary"].apply(lambda x: (x - min_salary) / (max_salary - min_salary))
#192 ms ± 9.08 ms per loop (mean ± std. dev. of 7 runs, 1 loop each)

#swifter.apply
%timeit df["Normalized_Salary"] = df["Salary"].swifter.apply(lambda x: (x - min_salary) / (max_salary - min_salary))
#83.5 ms ± 478 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

总结

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

https://avoid.overfit.cn/post/d38401bd97e2442d89a9099ec260bfac

作者:Okan Yenigün

正文完
 0