您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。