
Pandas 常用于数据处理与分析,梳理了 140 个 Pandas 要点,帮助驾驭各类数据分析任务。
import pandas as pd
data = {'姓名': ['张三', '李四', '王五'], '年龄': [25, 30, 35]}
df = pd.DataFrame(data)
print(df)data = [{'姓名': '张三', '年龄': 25}, {'姓名': '李四', '年龄': 30}]
df = pd.DataFrame(data)
print(df)df = pd.read_csv('data.csv', encoding='utf-8')
print(df.head())df = pd.read_excel('data.xlsx', sheet_name='Sheet1')
print(df.head())print(df.info())print(df.describe())print(df.head(3))print(df.tail(3))print(df.columns)print(df.index)ages = df['年龄']
print(ages)subset = df[['姓名', '年龄']]
print(subset)row = df.iloc[1] # 选择第二行
print(row)filtered = df[df['年龄'] > 30]
print(filtered)filtered = df[(df['年龄'] > 25) & (df['姓名'] != '张三')]
print(filtered)filtered = df[df['姓名'].isin(['张三', '李四'])]
print(filtered)filtered = df.query('年龄 > 25 and 姓名 != "张三"')
print(filtered)subset = df.loc[0:1, ['姓名', '年龄']]
print(subset)subset = df.iloc[0:2, 0:2]
print(subset)sample = df.sample(n=2)
print(sample)df.fillna(0, inplace=True) # 用0填充缺失值df.dropna(inplace=True)df.drop_duplicates(inplace=True)df.rename(columns={'姓名': 'name', '年龄': 'age'}, inplace=True)df.drop(columns=['age'], inplace=True)df['age'] = df['age'].astype('float')df['name'] = df['name'].str.lower()df['name'] = df['name'].str.strip()df['name'] = df['name'].replace('张三', '张小三')df['age'] = df['age'].apply(lambda x: x + 1)df['年龄加1'] = df['年龄'] + 1df['年龄段'] = ['青年' if age < 30 else '中年' for age in df['年龄']]grouped = df.groupby('年龄段')['年龄'].mean()
print(grouped)grouped = df.groupby('年龄段').agg({'年龄': ['mean', 'max']})
print(grouped)pivot = pd.pivot_table(df, values='年龄', index='姓名', aggfunc='mean')
print(pivot)cross = pd.crosstab(df['姓名'], df['年龄段'])
print(cross)sorted_df = df.sort_values('年龄', ascending=False)
print(sorted_df)sorted_df = df.sort_values(['年龄段', '年龄'], ascending=[True, False])
print(sorted_df)df['年龄分组'] = pd.cut(df['年龄'], bins=[0, 30, 40, 50])
print(df)dummies = pd.get_dummies(df['年龄段'])
print(dummies)df1 = pd.DataFrame({'A': [1, 2], 'B': [3, 4]})
df2 = pd.DataFrame({'A': [5, 6], 'B': [7, 8]})
merged = pd.concat([df1, df2])
print(merged)merged = pd.concat([df1, df2], axis=1)
print(merged)left = pd.DataFrame({'key': ['A', 'B'], 'value': [1, 2]})
right = pd.DataFrame({'key': ['A', 'C'], 'value': [3, 4]})
merged = pd.merge(left, right, on='key', how='inner')
print(merged)merged = pd.merge(left, right, on='key', how='left')
print(merged)merged = pd.merge(left, right, on='key', how='right')
print(merged)merged = pd.merge(left, right, on='key', how='outer')
print(merged)merged = pd.merge(left, right, left_index=True, right_index=True)
print(merged)merged = pd.merge(left, right, on=['key1', 'key2'])
print(merged)df1.append(df2, ignore_index=True)merged = pd.merge(left, right, on='key', suffixes=('_left', '_right'))
print(merged)dates = pd.date_range('20230101', periods=6)
df = pd.DataFrame({'date': dates, 'value': [1, 2, 3, 4, 5, 6]})df.set_index('date', inplace=True)resampled = df.resample('M').mean()
print(resampled)shifted = df.shift(1)
print(shifted)df['diff'] = df['value'].diff()
print(df)rolling = df['value'].rolling(window=2).mean()
print(rolling)expanding = df['value'].expanding().mean()
print(expanding)df['year'] = df.index.year
df['month'] = df.index.month
print(df)periods = pd.period_range('2023-01', '2023-06', freq='M')
print(periods)df.index = df.index.tz_localize('UTC').tz_convert('Asia/Shanghai')
print(df)df.plot.line()df.plot.bar()df.plot.hist()df.plot.box()df.plot.scatter(x='age', y='income')df.plot.pie(y='value')df.plot.area()import seaborn as sns
sns.heatmap(df.corr())df.plot(subplots=True, layout=(2, 2))import matplotlib.pyplot as plt
ax = df.plot()
ax.set_title('My Plot')
ax.set_xlabel('Date')
plt.show()arrays = [['A', 'A', 'B', 'B'], [1, 2, 1, 2]]
index = pd.MultiIndex.from_arrays(arrays, names=('letter', 'number'))
df = pd.DataFrame({'data': [10, 20, 30, 40]}, index=index)
print(df)stacked = df.stack()
print(stacked)
unstacked = stacked.unstack()
print(unstacked)pivoted = df.pivot(index='date', columns='category', values='value')
print(pivoted)melted = pd.melt(df, id_vars=['date'], value_vars=['A', 'B'])
print(melted)df['category'] = df['category'].astype('category')
print(df['category'].cat.categories)df = df.astype({'age': 'int8', 'income': 'float32'})
print(df.info())chunks = pd.read_csv('large_file.csv', chunksize=10000)
for chunk in chunks:
process(chunk)import swifter
df['new_col'] = df['col'].swifter.apply(lambda x: x*2)pd.set_option('display.max_rows', 100)
pd.set_option('display.max_columns', 50)%timeit df.groupby('category').mean()df.to_csv('output.csv', index=False)df.to_excel('output.xlsx', sheet_name='Sheet1')df.to_json('output.json', orient='records')df.to_html('output.html')from sqlalchemy import create_engine
engine = create_engine('sqlite:///output.db')
df.to_sql('table_name', engine)df = pd.read_sql('SELECT * FROM table_name', engine)dfs = pd.read_html(' http://example.com/tables.html ')df = pd.read_clipboard()df.to_parquet('output.parquet')df = pd.read_parquet('output.parquet')pd.set_option('display.max_columns', None)pd.set_option('display.max_rows', None)pd.set_option('display.precision', 2)with pd.option_context('display.max_rows', 10):
print(df)def highlight_max(s): is_max = s == s.max() return ['background-color: yellow' if v else '' for v in is_max]
df.style.apply(highlight_max)df.style.bar(color='#d65f5f')result = (df.query('age > 30')
.groupby('gender')
.agg({'income': 'mean'})
.sort_values('income', ascending=False))print(df.memory_usage(deep=True))df = df.convert_dtypes()%prun df.groupby('category').mean()df['full_name'] = df['first_name'] + ' ' + df['last_name']df['name_parts'] = df['full_name'].str.split(' ')df['first_letter'] = df['name'].str[0]df['area_code'] = df['phone'].str.extract(r'(\d{3})')df['clean_phone'] = df['phone'].str.replace(r'\D', '')df['has_com'] = df['email'].str.contains('.com')df['name_length'] = df['name'].str.len()df['id_padded'] = df['id'].str.pad(5, fillchar='0')df['clean_text'] = df['text'].str.replace('[^\w\s]', '')from collections import Counter
word_counts = Counter(' '.join(df['text']).split())df['rolling_avg'] = df['value'].rolling(window=7).mean()df['ewm'] = df['value'].ewm(span=7).mean()df['normalized'] = (df['value'] - df['value'].mean()) / df['value'].std()df['quantile'] = pd.qcut(df['value'], q=4, labels=False)correlation = df.corr()covariance = df.cov()from sklearn.decomposition import PCA
pca = PCA(n_components=2)
df_pca = pca.fit_transform(df.select_dtypes(include='number'))from sklearn.cluster import KMeans
kmeans = KMeans(n_clusters=3)
df['cluster'] = kmeans.fit_predict(df.select_dtypes(include='number'))df['is_outlier'] = (df['value'] - df['value'].mean()).abs() > 3 * df['value'].std()from statsmodels.tsa.seasonal import seasonal_decompose
result = seasonal_decompose(df['value'], model='additive', period=12)
result.plot()121、使用迭代器读取大文件
chunks = pd.read_csv('大文件.csv', chunksize=10000)
for chunk in chunks:
process(chunk)122、分类数据优化
df['类别列'] = df['类别列'].astype('category')123、使用eval表达式
df.eval('新列 = 列1 + 列2', inplace=True)124、使用query提高性能
df.query('年龄 > 30 & 性别 == "男"', inplace=True)125、使用at/iat快速访问
df.at[0, '列名'] = 100 # 比loc更快126、避免链式赋值
# 不好
df['列'][df['条件']] = 值
# 好
df.loc[df['条件'], '列'] = 值127、使用numpy操作
import numpy as np
df['新列'] = np.log(df['数值列'])128、避免循环
# 不好
for i in range(len(df)):
df.at[i, '新列'] = df.at[i, '列'] * 2
# 好
df['新列'] = df['列'] * 2129、内存使用分析
df.memory_usage(deep=True)130、释放内存
import gc
del df
gc.collect()131、分组应用函数
def custom_func(group):
return group['数值列'].mean() / group['数值列'].std()
df.groupby('分组列').apply(custom_func)132、映射函数
df['等级'] = df['分数'].map(lambda x: 'A' if x > 90 else 'B' if x > 80 else 'C')133、按行应用函数
df.apply(lambda row: row['列1'] + row['列2'], axis=1)134、分组聚合多个函数
df.groupby('部门').agg({'销售额': ['sum', 'mean'], '利润': 'max'})135、分组转换
df['部门平均'] = df.groupby('部门')['销售额'].transform('mean')136、分组过滤
df.groupby('部门').filter(lambda x: x['销售额'].mean() > 1000)137、滚动应用函数
df['滚动平均'] = df['数值列'].rolling(5).apply(lambda x: x.mean())138、扩展应用函数
df['累计百分比'] = df['数值列'].expanding().apply(lambda x: x[-1]/x.sum())139、分组时间重采样
df.groupby('产品').resample('W')['销售额'].sum()140、自定义聚合器
def top_n(df, n=3, column='销售额'):
return df.sort_values(column, ascending=False).head(n)
df.groupby('部门').apply(top_n)140个Pandas技巧能够高效处理各种数据分析任务。从基本的数据操作到处理时间序列、分类数据等的高级技术。在实际数据集上尝试这些技巧,有助于巩固对Pandas及其功能的理解,在实际项目中多加练习,将这些技巧融会贯通。
“无他,惟手熟尔”!有需要的用起来。
如果你觉得这篇文章有用,欢迎点赞、转发、收藏、留言、推荐❤!
本文分享自 Nicholas与Pypi 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!