一、数据读取与保存(I/O操作)

# 读取数据
df = pd.read_csv('file.csv')  # 最常用
df = pd.read_excel('file.xlsx')
df = pd.read_json('file.json')

# 保存数据
df.to_csv('output.csv', index=False)  # index=False很常用
df.to_excel('output.xlsx')

二、数据查看与基本信息

df.head()       # 查看前5行
df.tail()       # 查看后5行
df.info()       # 数据类型和内存信息
df.describe()   # 统计摘要
df.shape        # 维度
df.columns      # 列名
df.dtypes       # 列数据类型

三、数据选择与筛选

# 列选择
df['column']           # Series
df[['col1', 'col2']]   # DataFrame
# 行选择
df.loc[index]          # 按标签选择
df.iloc[row_index]     # 按位置选择
df.loc[df['col'] > 10] # 条件筛选
## 条件筛选(重要!)
# 单条件
df[df['score'] > 80]

# 多条件
df[(df['score'] > 80) & (df['age'] < 30)]  # AND
df[(df['score'] > 80) | (df['age'] < 30)]  # OR

# isin查询
df[df['city'].isin(['北京', '上海', '广州'])]

# 字符串包含
df[df['name'].str.contains('张')]

四、数据清洗与处理

# 缺失值处理
df.isnull().sum()      # 查看缺失值
df.dropna()            # 删除缺失值
df.fillna(value)       # 填充缺失值

# 重复值处理
df.duplicated().sum()  # 检查重复值
df.drop_duplicates()   # 删除重复值

# 数据类型转换
df['col'] = df['col'].astype('int')
df['date'] = pd.to_datetime(df['date'])

# 重命名列
df.rename(columns={'old': 'new'})

五、数据转换

# 新增列
df['new_col'] = df['col1'] + df['col2']

# 应用函数
df['col'].apply(lambda x: x*2)    # 标量运算
df.applymap(lambda x: x*2)        # 整个DataFrame

# map替换
df['gender'].map({'男': 'M', '女': 'F'})

# 向量化运算(推荐)
df['result'] = np.where(df['score'] >= 60, '及格', '不及格')

六、分组聚合(重要!)

# 基本分组
df.groupby('category')['value'].sum()

# 多重聚合
df.groupby('category').agg({
    'value1': 'sum',
    'value2': 'mean',
    'value3': ['min', 'max', 'count']
})

# 分组后应用自定义函数
df.groupby('group').apply(lambda x: x.sort_values('value').head(3))

七、数据合并与连接

# 合并
pd.concat([df1, df2])            # 纵向/横向拼接

# 连接(类似SQL)
pd.merge(left, right, on='key')  # 内连接
pd.merge(left, right, on='key', how='left')   # 左连接
pd.merge(left, right, on='key', how='outer')  # 全连接

八、数据透视表

pd.pivot_table(df, 
               values='sales',
               index='region',
               columns='month',
               aggfunc='sum',
               fill_value=0)

九、时间序列处理

# 时间转换
df['date'] = pd.to_datetime(df['date'])
df.set_index('date', inplace=True)

# 重采样
df.resample('M').sum()   # 按月
df.resample('D').mean()  # 按天

# 滚动窗口
df.rolling(window=7).mean()  # 7天移动平均

十、性能优化技巧

# 使用向量化操作代替循环
# 使用categorical类型处理重复字符串
# 使用query方法进行复杂筛选
df.query('age > 25 and salary > 50000')

# 使用eval进行表达式计算
df.eval('result = col1 + col2')
Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐