# Pandas數據分析實用小技巧有哪些
Pandas作為Python生態中最強大的數據分析工具庫,掌握其高效使用技巧能顯著提升數據處理效率。本文將系統介紹34個實用技巧,涵蓋數據讀取、清洗、轉換、分析和可視化全流程。
## 一、高效數據讀取技巧
### 1. 大數據集分塊讀取
```python
chunk_size = 100000
chunks = pd.read_csv('large_dataset.csv', chunksize=chunk_size)
for chunk in chunks:
process(chunk) # 自定義處理函數
dtypes = {'user_id': 'int32', 'price': 'float32'}
df = pd.read_csv('data.csv', dtype=dtypes)
cols = ['name', 'date', 'value']
df = pd.read_csv('data.csv', usecols=cols)
df = pd.read_csv('dates.csv', parse_dates=['order_date'])
def check_quality(df):
return pd.DataFrame({
'dtype': df.dtypes,
'missing': df.isna().sum(),
'unique': df.nunique()
})
df['age'].fillna(df['age'].median(), inplace=True) # 數值列
df['city'].fillna('Unknown', inplace=True) # 分類列
df['discount'] = np.where(df['amount'] > 1000, 0.2, 0.1)
df.drop_duplicates(subset=['user_id', 'date'], keep='last', inplace=True)
# 方法1: 布爾索引
df[(df['age'] > 30) & (df['city'] == 'Beijing')]
# 方法2: query方法
df.query("age > 30 and city == 'Beijing'")
# 方法3: loc條件篩選
df.loc[lambda x: (x['age'] > 30) & (x['city'] == 'Beijing')]
numeric_cols = df.select_dtypes(include=['int64', 'float64']).columns
df[df['price'].between(100, 200, inclusive='both')]
bins = [0, 18, 35, 60, 100]
labels = ['child', 'young', 'middle', 'senior']
df['age_group'] = pd.cut(df['age'], bins=bins, labels=labels)
df = pd.get_dummies(df, columns=['city'], prefix='city')
agg_funcs = {
'sales': ['sum', 'mean', 'max'],
'profit': lambda x: (x > 0).mean() # 自定義聚合
}
df.groupby('region').agg(agg_funcs)
df.set_index('timestamp').resample('W-MON')['value'].mean()
pd.merge(df1, df2, on='key', how='left', indicator=True)
pd.concat([df1, df2], axis=0, ignore_index=True)
diff = df1.compare(df2, align_axis=0)
# 不推薦
df[df['age'] > 30]['score'] = 100
# 推薦方式
df.loc[df['age'] > 30, 'score'] = 100
df.eval('profit = revenue - cost', inplace=True)
def reduce_mem_usage(df):
for col in df.columns:
col_type = df[col].dtype
if col_type != object:
c_min = df[col].min()
c_max = df[col].max()
if str(col_type)[:3] == 'int':
if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:
df[col] = df[col].astype(np.int8)
# 類似處理其他整數類型...
else:
# 處理浮點類型...
return df
df['7day_avg'] = df['price'].rolling(window=7).mean()
df['cum_max'] = df['value'].expanding().max()
df['rank'] = df.groupby('department')['sales'].rank(ascending=False)
pd.pivot_table(df, values='sales', index='region',
columns='quarter', aggfunc=np.sum,
margins=True, margins_name='Total')
df.plot(x='date', y=['revenue', 'cost'],
kind='line', figsize=(12, 6),
title='Revenue vs Cost Trend')
import seaborn as sns
corr = df.corr()
sns.heatmap(corr, annot=True, cmap='coolwarm')
pd.set_option('display.max_columns', 50)
pd.set_option('display.float_format', '{:.2f}'.format)
with pd.ExcelWriter('output.xlsx') as writer:
df1.to_excel(writer, sheet_name='Summary')
df2.to_excel(writer, sheet_name='Details')
# 固定比例抽樣
sample_df = df.sample(frac=0.1, random_state=42)
# 固定數量抽樣
sample_df = df.sample(n=1000)
test_df = pd.util.testing.makeDataFrame() # 20行4列隨機數據
from tqdm import tqdm
tqdm.pandas()
df['new_col'] = df['col'].progress_apply(complex_function)
(df.style
.highlight_max(color='lightgreen')
.format({'salary': "${:,.0f}"}))
df.info(memory_usage='deep') # 詳細內存使用情況
掌握這些Pandas技巧后,您將能夠: - 處理大型數據集時效率提升50%+ - 數據清洗代碼量減少60% - 復雜分析任務完成時間縮短70% - 自動化常規分析流程
建議收藏本文作為速查手冊,在實際工作中靈活組合使用這些技巧。隨著Pandas版本更新,持續關注新特性的加入將使您的數據分析能力持續進化。 “`
注:本文示例基于Pandas 1.3+版本,部分高級功能可能需要更新版本支持。實際應用時請根據數據特點調整參數。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。