目录列表
- pandas - @sharkdd
- DataFrame API
- 1. 创建 DataFrame
- 2. 查看数据
- 3. 选择数据
- 4. 数据过滤
- 5. 数据操作
- 6. 数据聚合
- 7. 数据合并
- 8. 数据转换
- 9. 数据导入导出
- 10. 其他方法
- 11. 数据索引
- 12. 数据过滤和条件选择
- 13. 数据转换和重塑
- 14. 时间序列处理
- 15. 数据合并与连接
- 16. 数据透视表
- 17. 交叉表
- 18. 数据可视化(与 Matplotlib 结合)
- 19. 处理分类数据
- 20. 处理缺失值的高级技巧
- 21. 性能优化
- 22. 自定义函数
- 23. 高级索引
- 24. 数据安全性
- 25. 处理异常值
- 26. 分组操作的高级技巧
- 27. 复杂的数据透视
- 28. 处理时间序列的高级技巧
- 29. 数据的批量处理
- 30. 数据清洗
- 31. 数据分区
- 32. 可视化增强
- 33. 数据的质量检查
- 34. 自定义数据类型
- 35. 高效数据存储
- 36. 处理大规模数据
- 37. 数据标准化和归一化
- 38. 处理文本数据
- 39. 数据集成
- 40. 使用条件格式化
- 41. 复杂的分组与合并
- 42. 自定义格式化输出
- 43. 使用 NumPy 进行计算
- 44. 自定义异常处理
- 45. 高级数据分析
- Series API
- 1. 创建 Series
- 2. 基本属性
- 3. 常用方法
- 4. 数据操作
- 5. 统计和聚合
- 6. 选择和过滤
- 7. 应用和映射
- 8. 字符串操作 (适用于字符串 Series)
- 9. 时间序列操作
- 10. 处理分类数据
- 11. 连接和合并
- 12. 自定义聚合
- 13. 统计函数的应用
- 14. 处理缺失值的更多方法
- 15. 复杂索引
- 16. 数据透视和分组
- 17. 自定义函数的使用
- 18. 复制和视图
- 19. 数据类型转换
- 20. 处理重复数据
- 21. 使用矢量化操作
- 22. 过滤和条件选择
- 23. 使用 `map()` 进行转换
- 24. 多重条件过滤
- 25. 使用 `shift()` 和 `diff()`
- 26. 处理字符串的更多操作
- 27. 使用 `cut()` 和 `qcut()`
- 28. 连接字符串
- 29. 使用 `isin()` 进行过滤
- 30. 使用 `str.split()` 进行字符串分割
- 31. 使用 `transform()`
- 32. 使用 `pipe()`
- 33. 使用 `combine_first()`
- 34. 使用 `reindex()`
- 35. 使用 `sample()`
- 36. 使用 `expanding()` 和 `rolling()`
- 37. 使用 `nsmallest()` 和 `nlargest()`
- 38. 使用 `str.extract()` 提取字符串中的模式
- 39. 使用 `str.contains()` 进行模式匹配
- 40. 使用 `str.replace()` 替换字符串中的模式
- 41. 使用 `str.split()` 分割字符串并扩展
- 42. 使用 `str.join()` 连接字符串
- 43. 使用 `duplicated()` 和 `drop_duplicates()`
- 44. 使用 `astype('category')` 进行分类数据
- 45. 使用 `apply()` 进行复杂操作
pandas - @sharkdd
DataFrame API
1. 创建 DataFrame
import pandas as pd
data = {
'Name': ['Alice', 'Bob', 'Charlie'],
'Age': [25, 30, 35],
'Score': [85.5, 90.0, 78.0]
}
df = pd.DataFrame(data)
- 说明:可以从字典、列表、Numpy 数组等创建 DataFrame,字典的键作为列名,值作为列的数据。
2. 查看数据
head(n)
df.head(2) # 返回前 2 行
tail(n)
df.tail(2) # 返回后 2 行
info()
df.info() # 显示 DataFrame 的简要信息,包含列名、数据类型和非空值数量
describe()
df.describe() # 返回数值列的统计信息,如均值、标准差等
3. 选择数据
loc[]
:基于标签选择数据(标签名)
df.loc[0] # 选择第一行
df.loc[:, 'Name'] # 选择 'Name' 列
iloc[]
:基于位置选择数据(行列号)
df.iloc[0, 1] # 选择第一行第二列的值
at[]
:快速获取单个值
df.at[0, 'Name'] # 获取第一行 'Name' 列的值
iat[]
:快速获取单个值
df.iat[0, 1] # 获取第一行第二列的值
4. 数据过滤
- 条件过滤
df[df['Age'] > 28] # 返回年龄大于 28 的行
isin()
:检查某列的值是否在指定列表中
df[df['Name'].isin(['Alice', 'Bob'])] # 选择名字为 Alice 或 Bob 的行
5. 数据操作
sort_values(by)
:按指定列排序
df.sort_values(by='Age', ascending=False) # 按年龄降序排序
drop(labels)
:删除指定行或列axis=0
表示沿着行的方向进行操作(即对行进行操作)。axis=1
表示沿着列的方向进行操作(即对列进行操作)。
df.drop('Score', axis=1, inplace=True) # 删除 'Score' 列
rename()
:重命名行或列
df.rename(columns={'Age': 'Years'}, inplace=True) # 将 'Age' 列重命名为 'Years'
fillna(value)
:用指定值填充缺失值
df.fillna(0, inplace=True) # 将缺失值填充为 0
dropna()
:删除含有缺失值的行或列
df.dropna(inplace=True) # 删除任何含有缺失值的行
6. 数据聚合
groupby()
grouped = df.groupby('Name').mean() # 按 'Name' 列分组并计算均值
agg()
:对分组后的数据应用多个聚合函数
df.groupby('Name').agg({'Age': 'mean', 'Score': 'sum'}) # 对 'Age' 计算均值,对 'Score' 计算总和
7. 数据合并
merge()
:根据某些列合并两个 DataFrame
df1 = pd.DataFrame({'key': ['A', 'B'], 'value': [1, 2]})
df2 = pd.DataFrame({'key': ['A', 'B'], 'value': [3, 4]})
merged = pd.merge(df1, df2, on='key') # 根据 'key' 列合并
concat()
:连接多个 DataFrame
df1 = pd.DataFrame({'A': [1, 2]})
df2 = pd.DataFrame({'A': [3, 4]})
concat_df = pd.concat([df1, df2], axis=0) # 按行连接
8. 数据转换
apply()
:应用自定义函数
df['Score'] = df['Score'].apply(lambda x: x * 2) # 将 'Score' 列的值乘以 2
pivot_table()
:创建数据透视表
pivot = df.pivot_table(values='Score', index='Name', columns='Age', aggfunc='mean')
melt()
:将宽格式数据转换为长格式
melted = pd.melt(df, id_vars=['Name'], value_vars=['Age', 'Score'])
9. 数据导入导出
to_csv()
:将 DataFrame 导出为 CSV 文件
df.to_csv('output.csv', index=False) # 不导出索引
read_csv()
:从 CSV 文件导入 DataFrame
df = pd.read_csv('input.csv')
to_excel()
:导出为 Excel 文件
df.to_excel('output.xlsx', index=False) # 不导出索引
read_excel()
:从 Excel 文件导入 DataFrame
df = pd.read_excel('input.xlsx')
10. 其他方法
duplicated()
:检查重复的行
df.duplicated() # 返回布尔系列,指示每行是否重复
drop_duplicates()
:删除重复的行
df.drop_duplicates(inplace=True) # 删除重复行
value_counts()
:统计某一列中每个值的频次
df['Name'].value_counts() # 统计 'Name' 列每个名字的出现频次
11. 数据索引
- 设置索引
df.set_index('Name', inplace=True) # 将 'Name' 列设置为索引
- 重置索引
df.reset_index(inplace=True) # 重置索引,默认索引会被创建
- 使用多重索引
df.set_index(['Name', 'Age'], inplace=True) # 使用多列设置多重索引
12. 数据过滤和条件选择
- 链式条件
filtered_df = df[(df['Age'] > 25) & (df['Score'] > 80)] # 使用多个条件过滤
- 使用
query()
方法
filtered_df = df.query('Age > 25 and Score > 80') # 使用查询语法进行过滤
13. 数据转换和重塑
- 使用
applymap()
:对 DataFrame 中的每个元素应用函数
df.applymap(lambda x: x * 2) # 将 DataFrame 中的每个值乘以 2
- 使用
stack()
和unstack()
:改变 DataFrame 的形状
stacked = df.stack() # 将 DataFrame 转换为 Series,行索引变为层级索引
unstacked = stacked.unstack() # 恢复原形状
14. 时间序列处理
- 创建时间序列 DataFrame
dates = pd.date_range('2024-01-01', periods=5)
df_time = pd.DataFrame({'Date': dates, 'Value': [1, 2, 3, 4, 5]})
- 设置日期为索引
df_time.set_index('Date', inplace=True)
- 重采样时间序列
df_time.resample('2D').sum() # 每 2 天重采样并求和
- 时间偏移
df_time.shift(1) # 将数据向下移动一行
15. 数据合并与连接
join()
:连接两个 DataFrame,基于索引**(比较concat)
**
df1 = pd.DataFrame({'A': [1, 2]}, index=['A', 'B'])
df2 = pd.DataFrame({'B': [3, 4]}, index=['A', 'B'])
joined = df1.join(df2) # 基于索引连接 默认是行索引 加上axis=1才能操作列索引
16. 数据透视表
- 使用
pivot_table()
创建透视表
pivot_df = df.pivot_table(values='Score', index='Name', columns='Age', aggfunc='mean')
- 处理缺失值的透视表
pivot_df = df.pivot_table(values='Score', index='Name', columns='Age', aggfunc='mean', fill_value=0)
17. 交叉表
- 使用
crosstab()
创建交叉表
pd.crosstab(df['Name'], df['Age']) # 统计 'Name' 和 'Age' 的交叉频次
18. 数据可视化(与 Matplotlib 结合)
- 简单绘图
import matplotlib.pyplot as plt
df['Score'].plot(kind='bar') # 绘制条形图
plt.show()
- 多种图表
df.plot(kind='line', x='Name', y='Score') # 绘制折线图
plt.show()
19. 处理分类数据
- 设置分类类型
df['Category'] = pd.Categorical(df['Category'])
- 使用分类数据的优势
df['Category'].cat.codes # 获取分类数据的编码
20. 处理缺失值的高级技巧
- 使用
interpolate()
填充缺失值
df['Score'].interpolate(method='linear', inplace=True) # 线性插值填充缺失值
21. 性能优化
- 使用
astype()
更改数据类型
df['Age'] = df['Age'].astype('int') # 将 'Age' 列转换为整型
- 使用
query()
优化性能
filtered_df = df.query('Age > 25')
22. 自定义函数
- 定义和应用自定义函数
def custom_function(x):
return x * 10
df['New_Score'] = df['Score'].apply(custom_function) # 应用自定义函数
23. 高级索引
xs()
方法获取交叉切片
df.xs('A', level='Name') # 获取 'Name' 为 A 的所有行
24. 数据安全性
- 使用
copy()
创建副本
df_copy = df.copy() # 创建 DataFrame 的副本,避免修改原始数据
25. 处理异常值
- 使用
clip()
限制值范围
df['Score'] = df['Score'].clip(lower=0, upper=100) # 将 'Score' 限制在 0 到 100 之间
26. 分组操作的高级技巧
transform()
:在分组后对每个组应用函数,并返回与原 DataFrame 形状相同的结果
df['Age'] = df.groupby('Name')['Age'].transform('mean') # 将每个 Name 的年龄替换为该组的均值
filter()
:基于某个条件过滤组
filtered_groups = df.groupby('Name').filter(lambda x: x['Score'].mean() > 80) # 只保留均值大于 80 的组
27. 复杂的数据透视
- 组合多个聚合函数
aggregated = df.groupby('Name').agg({'Age': ['min', 'max'], 'Score': 'mean'}) # 多个聚合函数
28. 处理时间序列的高级技巧
- 时间窗口
df_time['Rolling_Mean'] = df_time['Value'].rolling(window=2).mean() # 计算滚动均值
- 时间偏移
df_time['Shifted'] = df_time['Value'].shift(1) # 将 'Value' 列向下移动一行 可以取负值
29. 数据的批量处理
- 批量写入 CSV
df.to_csv('output.csv', mode='a', header=False) # 追加模式写入 CSV
- 批量读取数据
# 使用 glob 读取多个 CSV 文件
import glob
all_files = glob.glob("data/*.csv")
df_list = [pd.read_csv(file) for file in all_files]
combined_df = pd.concat(df_list, ignore_index=True)
30. 数据清洗
- 使用正则表达式处理字符串
df['Name'] = df['Name'].str.replace(r'[^\w\s]', '', regex=True) # 移除名字中的特殊字符
- 字符串分割
df[['First_Name', 'Last_Name']] = df['Name'].str.split(' ', expand=True) # 将名字分为两个新列
31. 数据分区
- 使用
pd.cut()
将连续数据分区
df['Age_Group'] = pd.cut(df['Age'], bins=[0, 18, 35, 60, 100], labels=['Child', 'Young Adult', 'Adult', 'Senior'])
32. 可视化增强
- 使用 Seaborn 进行高级可视化
import seaborn as sns
sns.boxplot(data=df, x='Name', y='Score') # 使用 Seaborn 绘制箱型图
33. 数据的质量检查
- 检查重复值
duplicates = df[df.duplicated()] # 返回重复的行
- 检查缺失值的比例
missing_ratio = df.isnull().mean() # 计算每列缺失值的比例
34. 自定义数据类型
- 使用自定义数据类型
from pandas.api.extensions import register_dataframe_accessor
@register_dataframe_accessor("my_custom")
class MyCustomAccessor:
def __init__(self, pandas_obj):
self._obj = pandas_obj
def show_shape(self):
return self._obj.shape
# 使用自定义访问器
df.my_custom.show_shape()
35. 高效数据存储
- 使用 HDF5 格式存储大数据
df.to_hdf('data.h5', key='df', mode='w') # 写入 HDF5 文件
df_hdf = pd.read_hdf('data.h5', 'df') # 从 HDF5 文件读取
36. 处理大规模数据
- 使用 Dask 处理大数据
import dask.dataframe as dd
ddf = dd.read_csv('large_file.csv') # 使用 Dask 读取大文件
37. 数据标准化和归一化
- 标准化
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
df[['Score']] = scaler.fit_transform(df[['Score']]) # 将 'Score' 标准化
- 归一化
df['Normalized_Score'] = (df['Score'] - df['Score'].min()) / (df['Score'].max() - df['Score'].min()) # 归一化
38. 处理文本数据
- 分词
df['Words'] = df['Description'].str.split() # 将描述列中的文本分词
- 计算词频
from collections import Counter
word_counts = Counter(word for words in df['Words'] for word in words) # 计算词频
39. 数据集成
- 使用
pd.concat()
进行数据集成
combined_df = pd.concat([df1, df2], axis=1) # 按列合并
40. 使用条件格式化
- 条件格式化显示
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, subset=['Score']) # 高亮显示 'Score' 列最大值
41. 复杂的分组与合并
- 多条件分组
grouped = df.groupby(['Name', 'Age'])['Score'].sum().reset_index() # 按多个条件分组
42. 自定义格式化输出
- 格式化 DataFrame 输出
pd.options.display.float_format = '{:,.2f}'.format # 设置浮点数的输出格式
43. 使用 NumPy 进行计算
- 结合 NumPy 进行高效计算
import numpy as np
df['LogScore'] = np.log(df['Score']) # 计算 'Score' 的对数
44. 自定义异常处理
- 在处理数据时使用异常处理
try:
df['Age'] = df['Age'].astype(int)
except ValueError:
print("转换失败,存在非整数值")
45. 高级数据分析
- 使用
pivot()
进行数据重塑
pivot_df = df.pivot(index='Name', columns='Age', values='Score') # 重塑数据
Series API
1. 创建 Series
import pandas as pd
# 从列表创建 Series
s = pd.Series([1, 2, 3, 4, 5])
print(s)
2. 基本属性
# 获取索引
print(s.index) # 输出: RangeIndex(start=0, stop=5, step=1)
# 获取值
print(s.values) # 输出: [1 2 3 4 5]
# 获取形状
print(s.shape) # 输出: (5,)
# 获取数据类型
print(s.dtype) # 输出: dtype('O') 表示Object对象
3. 常用方法
# 返回前3个元素
print(s.head(3)) # 输出: 0 1
# 1 2
# 2 3
# 返回后3个元素
print(s.tail(3)) # 输出: 2 3
# 3 4
# 4 5
# 描述性统计
print(s.describe()) # 输出: count 5.0
# mean 3.0
# std 1.581
# min 1.0
# 25% 2.0
# 50% 3.0
# 75% 4.0
# max 5.0
# 统计每个唯一值的出现次数
print(s.value_counts()) # 输出: 1 1
# 2 1
# 3 1
# 4 1
# 5 1
4. 数据操作
# 填充缺失值
s_with_nan = pd.Series([1, 2, None, 4, 5])
print(s_with_nan.fillna(0)) # 输出: 0 1.0
# 1 2.0
# 2 0.0
# 3 4.0
# 4 5.0
# 删除缺失值
print(s_with_nan.dropna()) # 输出: 0 1.0
# 1 2.0
# 3 4.0
# 4 5.0
# 替换值
print(s.replace(3, 99)) # 输出: 0 1
# 1 2
# 2 99
# 3 4
# 4 5
5. 统计和聚合
# 计算总和
print(s.sum()) # 输出: 15
# 计算均值
print(s.mean()) # 输出: 3.0
# 计算中位数
print(s.median()) # 输出: 3.0
# 获取最大值和最小值
print(s.min()) # 输出: 1
print(s.max()) # 输出: 5
# 计算标准差
print(s.std()) # 输出: 1.581
6. 选择和过滤
# 使用布尔索引过滤
print(s[s > 3]) # 输出: 3 4
# 4 5
# 按位置选择元素
print(s.iloc[1]) # 输出: 2
# 按标签选择元素
print(s.loc[2]) # 输出: 3
7. 应用和映射
# 将函数应用于每个元素
print(s.apply(lambda x: x ** 2)) # 输出: 0 1
# 1 4
# 2 9
# 3 16
# 4 25
# 使用字典映射
mapping = {1: 'One', 2: 'Two', 3: 'Three'}
print(s.map(mapping)) # 输出: 0 One
# 1 Two
# 2 Three
# 3 NaN
# 4 NaN
8. 字符串操作 (适用于字符串 Series)
# 创建字符串 Series
str_series = pd.Series(['apple', 'banana', 'cherry'])
# 转换为小写
print(str_series.str.lower()) # 输出: 0 apple
# 1 banana
# 2 cherry
# 检查是否包含特定模式
print(str_series.str.contains('a')) # 输出: 0 True
# 1 True
# 2 False
9. 时间序列操作
如果你的 Series 包含时间数据,Pandas 提供了强大的时间序列功能。
# 创建时间序列
date_range = pd.date_range(start='2023-01-01', periods=5)
time_series = pd.Series([1, 2, 3, 4, 5], index=date_range)
print(time_series)
10. 处理分类数据
你可以将 Series 转换为分类数据,以提高性能和节省内存。
# 创建分类 Series
category_series = pd.Series(['a', 'b', 'a', 'c'], dtype='category')
print(category_series)
print(category_series.cat.categories) # 输出: Index(['a', 'b', 'c'], dtype='object')
11. 连接和合并
你可以将多个 Series 合并为一个 Series。
s1 = pd.Series([1, 2, 3])
s2 = pd.Series([4, 5, 6])
combined = pd.concat([s1, s2])
print(combined) # 输出: 0 1
# 1 2
# 2 3
# 0 4
# 1 5
# 2 6
12. 自定义聚合
你可以使用 agg
方法自定义聚合操作。
# 自定义聚合操作
print(s.agg(['sum', 'mean', 'max'])) # 输出:
# sum 15.0
# mean 3.0
# max 5.0
13. 统计函数的应用
许多统计函数可以直接应用于 Series。
# 计算累积和
print(s.cumsum()) # 输出: 0 1
# 1 3
# 2 6
# 3 10
# 4 15
# 计算移动平均
print(s.rolling(window=2).mean()) # 输出: 0 NaN
# 1 1.5
# 2 2.5
# 3 3.5
# 4 4.5
14. 处理缺失值的更多方法
# 插值法填充缺失值
s_with_nan = pd.Series([1, 2, None, 4, 5])
print(s_with_nan.interpolate()) # 输出: 0 1.0
# 1 2.0
# 2 3.0
# 3 4.0
# 4 5.0
15. 复杂索引
你可以使用多层索引(MultiIndex)来处理更复杂的数据。
# 创建多层索引 Series
arrays = [['A', 'A', 'B', 'B'], [1, 2, 1, 2]]
index = pd.MultiIndex.from_arrays(arrays, names=('letters', 'numbers'))
multi_index_series = pd.Series([1, 2, 3, 4], index=index)
print(multi_index_series)
16. 数据透视和分组
使用 groupby
方法对 Series 进行分组和聚合。
# 创建示例 DataFrame
data = {'Category': ['A', 'B', 'A', 'B', 'A'],
'Values': [10, 20, 30, 40, 50]}
df = pd.DataFrame(data)
# 按类别分组并计算总和
grouped = df.groupby('Category')['Values'].sum()
print(grouped)
17. 自定义函数的使用
你可以应用自定义函数进行复杂的操作。
# 自定义函数
def custom_func(x):
return x ** 2 + 1
print(s.apply(custom_func)) # 输出: 0 2
# 1 5
# 2 10
# 3 17
# 4 26
18. 复制和视图
理解 Series 的视图和复制行为非常重要。
# 创建 Series
s_original = pd.Series([1, 2, 3])
# 复制 Series
s_copy = s_original.copy()
# 修改原 Series 不影响复制的 Series
s_original[0] = 100
print(s_original) # 输出: 0 100
# 1 2
# 2 3
print(s_copy) # 输出: 0 1
# 1 2
# 2 3
19. 数据类型转换
你可以通过 astype()
方法转换 Series 的数据类型。
# 创建 Series
s = pd.Series(['1', '2', '3'])
# 转换为整数类型
s_int = s.astype(int)
print(s_int) # 输出: 0 1
# 1 2
# 2 3
20. 处理重复数据
可以使用 duplicated()
和 drop_duplicates()
方法处理重复值。
# 创建带重复值的 Series
s = pd.Series([1, 2, 2, 3, 4, 4, 5])
# 查找重复值
print(s.duplicated()) # 输出: 0 False
# 1 False
# 2 True
# 3 False
# 4 True
# 5 False
# 6 False
# 删除重复值
print(s.drop_duplicates()) # 输出: 0 1
# 1 2
# 3 3
# 4 4
# 6 5
21. 使用矢量化操作
Pandas 支持对 Series 进行矢量化操作,这可以提高性能。
# 矢量化操作
s = pd.Series([1, 2, 3, 4, 5])
s_squared = s ** 2 # 每个元素平方
print(s_squared) # 输出: 0 1
# 1 4
# 2 9
# 3 16
# 4 25
22. 过滤和条件选择
你可以使用复杂的条件进行过滤。
# 创建 Series
s = pd.Series([10, 20, 30, 40, 50])
# 条件选择(大于 25 且小于 45)
filtered = s[(s > 25) & (s < 45)]
print(filtered) # 输出: 3 40
# dtype: int64
23. 使用 map()
进行转换
map()
方法可以用于将 Series 中的值映射到新值。
# 创建 Series
s = pd.Series(['cat', 'dog', 'cat', 'bird'])
# 映射到新值
mapping = {'cat': 'feline', 'dog': 'canine', 'bird': 'avian'}
mapped_series = s.map(mapping)
print(mapped_series) # 输出: 0 feline
# 1 canine
# 2 feline
# 3 NaN
24. 多重条件过滤
你可以使用 np.select()
进行多重条件过滤。
import numpy as np
# 创建 Series
s = pd.Series([1, 2, 3, 4, 5])
# 多重条件
conditions = [
(s < 3),
(s >= 3) & (s < 5),
(s >= 5)
]
choices = ['low', 'medium', 'high']
# 使用 np.select()
result = np.select(conditions, choices, default='unknown')
print(result) # 输出: ['low' 'low' 'medium' 'medium' 'unknown']
25. 使用 shift()
和 diff()
这些方法可以用于时间序列分析。
# 创建 Series
s = pd.Series([1, 2, 3, 4, 5])
# 使用 shift()
shifted = s.shift(1)
print(shifted) # 输出: 0 NaN
# 1 1.0
# 2 2.0
# 3 3.0
# 4 4.0
# 使用 diff()
differences = s.diff()
print(differences) # 输出: 0 NaN
# 1 1.0
# 2 1.0
# 3 1.0
# 4 1.0
26. 处理字符串的更多操作
如果你的 Series 包含字符串数据,Pandas 提供了多种字符串操作。
# 创建字符串 Series
str_series = pd.Series(['apple', 'banana', 'cherry'])
# 字符串长度
print(str_series.str.len()) # 输出: 0 5
# 1 6
# 2 6
# 字符串拼接
print(str_series.str.cat(sep=', ')) # 输出: 'apple, banana, cherry'
27. 使用 cut()
和 qcut()
你可以将连续数据分箱。
# 创建连续数据 Series
s = pd.Series([1, 7, 5, 4, 2, 8, 6, 3])
# 使用 cut()
bins = [0, 3, 6, 9]
labels = ['low', 'medium', 'high']
binned = pd.cut(s, bins=bins, labels=labels)
print(binned) # 输出: 0 low
# 1 high
# 2 high
# 3 low
# 4 low
# 5 high
# 6 high
# 7 high
# 使用 qcut() 进行等频分箱
q_binned = pd.qcut(s, q=3, labels=['low', 'medium', 'high'])
print(q_binned) # 输出: 0 low
# 1 high
# 2 high
# 3 low
# 4 low
# 5 high
# 6 high
# 7 high
28. 连接字符串
使用 str.cat()
方法连接字符串。
# 创建字符串 Series
s1 = pd.Series(['A', 'B', 'C'])
s2 = pd.Series(['D', 'E', 'F'])
# 连接字符串
result = s1.str.cat(s2, sep='-')
print(result) # 输出: 0 A-D
# 1 B-E
# 2 C-F
29. 使用 isin()
进行过滤
检查 Series 中的值是否存在于给定的列表中。
# 创建 Series
s = pd.Series([1, 2, 3, 4, 5])
# 检查是否在给定列表中
filtered = s[s.isin([1, 3, 5])]
print(filtered) # 输出: 0 1
# 2 3
# 4 5
30. 使用 str.split()
进行字符串分割
分割字符串并返回一个新的 Series。
# 创建字符串 Series
s = pd.Series(['apple,banana,cherry', 'dog,cat', 'car,bike'])
# 分割字符串
split_series = s.str.split(',')
print(split_series) # 输出: 0 [apple, banana, cherry]
# 1 [dog, cat]
# 2 [car, bike]
31. 使用 transform()
transform()
方法可以对分组后的数据进行变换操作,返回与原数据相同长度的 Series。
# 创建示例 DataFrame
df = pd.DataFrame({
'Category': ['A', 'A', 'B', 'B', 'A'],
'Values': [10, 20, 30, 40, 50]
})
# 按类别计算每组的均值,并返回与原 DataFrame 长度相同的 Series
df['Mean_Values'] = df.groupby('Category')['Values'].transform('mean')
print(df)
32. 使用 pipe()
pipe()
方法允许你将 Series 传递给一个自定义函数。
# 自定义函数
def custom_function(s):
return s + 10
# 创建 Series
s = pd.Series([1, 2, 3])
# 使用 pipe()
result = s.pipe(custom_function)
print(result) # 输出: 0 11
# 1 12
# 2 13
33. 使用 combine_first()
这个方法可以用来将两个 Series 进行合并,优先选择第一个 Series 的值。
# 创建两个 Series
s1 = pd.Series([1, 2, None, 4])
s2 = pd.Series([10, None, 30, 40])
# 使用 combine_first()
combined = s1.combine_first(s2)
print(combined) # 输出: 0 1.0
# 1 2.0
# 2 30.0
# 3 4.0
34. 使用 reindex()
reindex()
方法可以调整 Series 的索引。
# 创建 Series
s = pd.Series([1, 2, 3], index=['a', 'b', 'c'])
# 重新索引
reindexed = s.reindex(['a', 'b', 'c', 'd'])
print(reindexed) # 输出: a 1.0
# b 2.0
# c 3.0
# d NaN
35. 使用 sample()
sample()
方法可以随机抽样 Series 中的元素。
# 创建 Series
s = pd.Series([1, 2, 3, 4, 5])
# 随机抽样 3 个元素
sampled = s.sample(n=3)
print(sampled)
36. 使用 expanding()
和 rolling()
这两个方法用于计算扩展窗口和滚动窗口的聚合。
# 创建 Series
s = pd.Series([1, 2, 3, 4, 5])
# 扩展窗口的总和
expanding_sum = s.expanding().sum()
print(expanding_sum) # 输出: 0 1
# 1 3
# 2 6
# 3 10
# 4 15
# 滚动窗口的总和(窗口大小为 2)
rolling_sum = s.rolling(window=2).sum()
print(rolling_sum) # 输出: 0 NaN
# 1 3.0
# 2 5.0
# 3 7.0
# 4 9.0
37. 使用 nsmallest()
和 nlargest()
这两个方法可以快速获取 Series 中的前 n 个最小值或最大值。
# 创建 Series
s = pd.Series([5, 1, 2, 3, 4])
# 获取最小的两个值
smallest = s.nsmallest(2)
print(smallest) # 输出: 1 1
# 2 2
# 获取最大的两个值
largest = s.nlargest(2)
print(largest) # 输出: 0 5
# 4 4
38. 使用 str.extract()
提取字符串中的模式
用于从字符串中提取特定模式。
# 创建字符串 Series
s = pd.Series(['abc123', 'def456', 'ghi789'])
# 提取数字
extracted = s.str.extract('(\d+)')
print(extracted) # 输出: 0
# 0 123
# 1 456
# 2 789
39. 使用 str.contains()
进行模式匹配
检查 Series 中的每个字符串是否包含特定的子串。
# 创建字符串 Series
s = pd.Series(['apple', 'banana', 'cherry'])
# 检查是否包含 'a'
contains_a = s.str.contains('a')
print(contains_a) # 输出: 0 True
# 1 True
# 2 False
40. 使用 str.replace()
替换字符串中的模式
# 创建字符串 Series
s = pd.Series(['cat', 'dog', 'catfish'])
# 替换 'cat' 为 'feline'
replaced = s.str.replace('cat', 'feline')
print(replaced) # 输出: 0 feline
# 1 dog
# 2 felinefish
41. 使用 str.split()
分割字符串并扩展
可以将字符串分割并展开到多个列。
# 创建字符串 Series
s = pd.Series(['A,B,C', 'D,E,F', 'G,H,I'])
# 分割并展开
expanded = s.str.split(',', expand=True)
print(expanded) # 输出:
# 0 1 2
# 0 A B C
# 1 D E F
# 2 G H I
42. 使用 str.join()
连接字符串
将 Series 中的字符串连接为一个字符串。
# 创建字符串 Series
s = pd.Series(['A', 'B', 'C'])
# 连接字符串
joined = s.str.cat(sep=', ')
print(joined) # 输出: 'A, B, C'
43. 使用 duplicated()
和 drop_duplicates()
检查和删除重复的值。
# 创建 Series
s = pd.Series([1, 2, 2, 3, 4, 4, 5])
# 检查重复
duplicates = s.duplicated()
print(duplicates) # 输出: 0 False
# 1 False
# 2 True
# 3 False
# 4 True
# 5 False
# 6 False
# 删除重复值
unique = s.drop_duplicates()
print(unique) # 输出: 0 1
# 1 2
# 3 3
# 4 4
# 6 5
44. 使用 astype('category')
进行分类数据
将 Series 转换为分类类型,优化内存使用和性能。
# 创建 Series
s = pd.Series(['apple', 'banana', 'apple', 'orange'])
# 转换为分类类型
s_category = s.astype('category')
print(s_category)
print(s_category.cat.categories) # 输出: Index(['apple', 'banana', 'orange'], dtype='object')
45. 使用 apply()
进行复杂操作
可以使用 apply()
方法将函数应用于 Series 的每个元素。
# 创建 Series
s = pd.Series([1, 2, 3, 4, 5])
# 应用自定义函数
def square(x):
return x ** 2
squared = s.apply(square)
print(squared) # 输出: 0 1
# 1 4
# 2 9
# 3 16
# 4 25