十段代碼讓你掌握Python Polars,高性能數(shù)據(jù)處理和分析工具
在數(shù)據(jù)處理與分析領(lǐng)域,高效應(yīng)對大規(guī)模數(shù)據(jù)集是一項(xiàng)核心挑戰(zhàn)。Python 的 Polars 庫作為一款高性能工具,為開發(fā)者提供了強(qiáng)大助力,能大幅提升數(shù)據(jù)處理的速度與效率。
本文向讀者全面介紹 Polars 庫,從其獨(dú)特特性、便捷的安裝方式,到基礎(chǔ)操作與高級應(yīng)用技巧,還會探討它在實(shí)際項(xiàng)目中的廣泛應(yīng)用場景,助力讀者深入掌握并靈活運(yùn)用這一工具,為數(shù)據(jù)處理工作帶來質(zhì)的飛躍。
1 Polars簡介
Polars是一個基于Apache Arrow構(gòu)建的高性能數(shù)據(jù)處理庫,專為快速進(jìn)行數(shù)據(jù)幀操作而設(shè)計(jì)。
與Pandas不同,Polars使用內(nèi)存映射和多線程技術(shù),實(shí)現(xiàn)更快的數(shù)據(jù)處理。對于大規(guī)模數(shù)據(jù)集,Polars是理想之選,它擁有豐富的特性和靈活的API,讓數(shù)據(jù)分析變得更快速、更輕松。
1.1安裝
使用pip可以輕松安裝Polars:
pip install polars
1.2 主要特性
- 高性能數(shù)據(jù)幀操作:能快速創(chuàng)建、篩選、選擇和轉(zhuǎn)換數(shù)據(jù)幀。
- 多線程計(jì)算:通過多線程提升數(shù)據(jù)處理速度。
- 靈活的表達(dá)式API:可執(zhí)行復(fù)雜的數(shù)據(jù)操作和計(jì)算。
- 內(nèi)存映射:利用內(nèi)存映射高效處理大規(guī)模數(shù)據(jù)集。
- 數(shù)據(jù)聚合和分組:執(zhí)行高級聚合和分組操作。
2 基礎(chǔ)用法示例
2.1 創(chuàng)建數(shù)據(jù)幀
以下是使用Polars創(chuàng)建簡單數(shù)據(jù)幀的方法:
import polars as pl
# 創(chuàng)建示例數(shù)據(jù)
data = {'date': pl.date_range(start='2021-01-01', end='2021-01-10'),
'open': [100, 102, 101, 103, 104, 105, 106, 107, 108, 109],
'high': [101, 103, 102, 104, 105, 106, 107, 108, 109, 110],
'low': [99, 101, 100, 102, 103, 104, 105, 106, 107, 108],
'close': [100, 102, 101, 103, 104, 105, 106, 107, 108, 109],
'volume': [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900]}
# 創(chuàng)建數(shù)據(jù)幀
df = pl.DataFrame(data)
print(df)
2.2 基礎(chǔ)數(shù)據(jù)操作
Polars提供了類似Pandas的操作,如篩選、選擇和轉(zhuǎn)換數(shù)據(jù):
import polars as pl
# 創(chuàng)建示例數(shù)據(jù)幀
data = {'date': pl.date_range(start='2021-01-01', end='2021-01-10'),
'open': [100, 102, 101, 103, 104, 105, 106, 107, 108, 109],
'high': [101, 103, 102, 104, 105, 106, 107, 108, 109, 110],
'low': [99, 101, 100, 102, 103, 104, 105, 106, 107, 108],
'close': [100, 102, 101, 103, 104, 105, 106, 107, 108, 109],
'volume': [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900]}
df = pl.DataFrame(data)
# 篩選數(shù)據(jù)
filtered_df = df.filter(pl.col("close") > 105)
# 選擇特定列
selected_df = df.select(["date", "close"])
# 創(chuàng)建新列
df = df.with_column((pl.col("high") - pl.col("low")).alias("range"))
print(filtered_df)
print(selected_df)
print(df)
2.3 數(shù)據(jù)聚合
Polars支持高效的聚合操作,如計(jì)算均值或總和:
import polars as pl
# 創(chuàng)建示例數(shù)據(jù)幀
data = {'date': pl.date_range(start='2021-01-01', end='2021-01-10'),
'open': [100, 102, 101, 103, 104, 105, 106, 107, 108, 109],
'high': [101, 103, 102, 104, 105, 106, 107, 108, 109, 110],
'low': [99, 101, 100, 102, 103, 104, 105, 106, 107, 108],
'close': [100, 102, 101, 103, 104, 105, 106, 107, 108, 109],
'volume': [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900]}
df = pl.DataFrame(data)
# 計(jì)算平均收盤價
avg_close = df.select(pl.col("close").mean()).to_series()
print(avg_close)
3 高級特性與技巧
3.1 多線程計(jì)算
Polars使用多線程加速數(shù)據(jù)處理:
import polars as pl
# 創(chuàng)建大規(guī)模數(shù)據(jù)集
data = {'date': pl.date_range(start='2021-01-01', end='2022-01-01'),
'value': pl.arange(1, 366)}
df = pl.DataFrame(data)
# 使用多線程計(jì)算總和
total_value = df.select(pl.sum("value")).to_series()
print(total_value)
3.2 內(nèi)存映射
利用內(nèi)存映射高效處理大規(guī)模數(shù)據(jù)集:
import polars as pl
# 創(chuàng)建示例數(shù)據(jù)
data = {'date': pl.date_range(start='2021-01-01', end='2021-01-10'),
'open': [100, 102, 101, 103, 104, 105, 106, 107, 108, 109],
'high': [101, 103, 102, 104, 105, 106, 107, 108, 109, 110],
'low': [99, 101, 100, 102, 103, 104, 105, 106, 107, 108],
'close': [100, 102, 101, 103, 104, 105, 106, 107, 108, 109],
'volume': [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900]}
df = pl.DataFrame(data)
# 保存為Parquet文件
df.write_parquet('example.parquet')
# 使用內(nèi)存映射加載數(shù)據(jù)
df_mmap = pl.scan_parquet('example.parquet')
print(df_mmap.collect())
3.3 表達(dá)式API
Polars的表達(dá)式API支持復(fù)雜的數(shù)據(jù)操作:
import polars as pl
# 創(chuàng)建示例數(shù)據(jù)幀
data = {'date': pl.date_range(start='2021-01-01', end='2021-01-10'),
'open': [100, 102, 101, 103, 104, 105, 106, 107, 108, 109],
'high': [101, 103, 102, 104, 105, 106, 107, 108, 109, 110],
'low': [99, 101, 100, 102, 103, 104, 105, 106, 107, 108],
'close': [100, 102, 101, 103, 104, 105, 106, 107, 108, 109],
'volume': [1000, 1100, 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900]}
df = pl.DataFrame(data)
# 使用表達(dá)式API計(jì)算極差
df = df.with_column((pl.col("high") - pl.col("low")).alias("range"))
# 計(jì)算平均極差
avg_range = df.select(pl.col("range").mean()).to_series()
print(avg_range)
4 實(shí)際應(yīng)用案例
4.1 實(shí)時數(shù)據(jù)分析
使用Polars進(jìn)行實(shí)時數(shù)據(jù)分析:
import polars as pl
import numpy as np
# 模擬實(shí)時數(shù)據(jù)流
data = {'time': pl.date_range(start='2021-01-01', end='2021-01-10'),
'value': np.random.randn(10)}
# 轉(zhuǎn)換為Polars數(shù)據(jù)幀
df = pl.DataFrame(data)
# 計(jì)算滾動均值
df = df.with_column(pl.col('value').rolling_mean(window_size=3).alias('rolling_mean'))
print(df)
4.2 大規(guī)模地理空間數(shù)據(jù)處理
用Polars處理大規(guī)模地理空間數(shù)據(jù)集:
import polars as pl
# 創(chuàng)建示例地理空間數(shù)據(jù)
data = {'latitude': [40.7128, 34.0522, 41.8781, 29.7604, 39.7392],
'longitude': [-74.0060, -118.2437, -87.6298, -95.3698, -104.9903],
'population': [8398748, 3990456, 2705994, 2325502, 716492]}
df = pl.DataFrame(data)
# 計(jì)算平均緯度和經(jīng)度
avg_lat_lon = df.select([pl.col("latitude").mean().alias("avg_latitude"),
pl.col("longitude").mean().alias("avg_longitude")])
print(avg_lat_lon)
4.3 金融數(shù)據(jù)分析
使用Polars分析金融數(shù)據(jù):
import polars as pl
# 創(chuàng)建示例金融數(shù)據(jù)
data = {'date': pl.date_range(start='2021-01-01', end='2021-01-10'),
'close': [100, 102, 101, 103, 104, 105, 106, 107, 108, 109]}
df = pl.DataFrame(data)
# 計(jì)算收益率
df = df.with_column((pl.col("close") / pl.col("close").shift(1) - 1).alias("return"))
# 計(jì)算月度收益率
monthly_returns = df.groupby(pl.col("date").dt.month()).agg(pl.col("return").sum().alias("monthly_return"))
print(monthly_returns)