[Python]库Pandas应用总结
1.Series一维数组
import pandas as pd
import numpy as np#创建一维数据Series
s = pd.Series([1, 3, 5, np.nan, 6, 8])
print(s)
结果:
0 1.0
1 3.0
2 5.0
3 NaN
4 6.0
5 8.0
dtype: float64
2.DataFrame二维表格数据
比较重要的数据结构,类似于Excel表格获取SQL表
df = pd.DataFrame({'姓名': ['张三', '李四', '王五'],'年龄': [22, 21, 19],'城市': ['西安', '北京', '广州']}
)
print(df)结果:姓名 年龄 城市
0 张三 22 西安
1 李四 21 北京
2 王五 19 广州
3.数据的读取和写入
3.1.读取数据
读取csv数据
#数据的读取写入
#读取csv文件数据,python中配置路径反斜杠\是转译字符,\r表示回车,\n表示换行
#解决方案一:使用原始字符串pd.read_csv(r"D:\regression_test.csv"),
# 或者双反斜杠pd.read_csv(r"D:\\regression_test.csv")
df_csv = pd.read_csv(r"D:\regression_test.csv")
#df_csv = pd.read_csv("D:\\regression_test.csv")
print(df_csv)结果:fixed_acidity volatile_acidity citric_acid ... sulphates alcohol quality
0 7.4 0.700 0.00 ... 0.56 9.4 5
1 7.8 0.880 0.00 ... 0.68 9.8 5
2 7.8 0.760 0.04 ... 0.65 9.8 5
3 11.2 0.280 0.56 ... 0.58 9.8 6
4 7.4 0.700 0.00 ... 0.56 9.4 5
... ... ... ... ... ... ... ...
1594 6.2 0.600 0.08 ... 0.58 10.5 5
1595 5.9 0.550 0.10 ... 0.76 11.2 6
1596 6.3 0.510 0.13 ... 0.75 11.0 6
1597 5.9 0.645 0.12 ... 0.71 10.2 5
1598 6.0 0.310 0.47 ... 0.66 11.0 6
读取Excel数据
#pd.read_excel读取excel需要配置sheet名称,并且依赖openpyxl,需要安装库df_excel = pd.read_excel(r"D:\test.xlsx", sheet_name='Sheet1')
print(df_excel)结果:姓名 年龄 城市
0 张三 23 北京
3.2.写入数据
#index=False表示是否将索引写入数据,False表示不写入
df.to_excel(r'D:\test.xlsx', index=False)
df_excel = pd.read_excel(r"D:\test.xlsx", sheet_name='Sheet1')
print(df_excel)姓名 年龄 城市
张三 25 北京
李四 30 上海
王五 35 广州
4.查看数据
#查看前五行数据
df_csv.head()
# 查看后5行
df.tail()
# 查看数据形状,(行,列)
print(df_csv.shape)
#查看数据类型,每一列数据类型,整个数据类型
print(df_csv.dtypes)
# 查看统计信息
print(df.describe())
# 查看索引信息
print(df.index)
# 查看列名
print(df.columns)(1599, 12)
fixed_acidity float64
volatile_acidity float64
citric_acid float64
residual_sugar float64
chlorides float64
free_sulfur_dioxide float64
total_sulfur_dioxide float64
density float64
pH float64
sulphates float64
alcohol float64
quality int64
dtype: object年龄
count 3.000000
mean 20.666667
std 1.527525
min 19.000000
25% 20.000000
50% 21.000000
75% 21.500000
max 22.000000
RangeIndex(start=0, stop=3, step=1)
Index(['姓名', '年龄', '城市'], dtype='object')
5.选择数据与过滤
5.1.选择列
#选择单列
print(df['姓名'])0 张三
1 李四
2 王五
Name: 姓名, dtype: object# 选择多列
print(df[['姓名', '年龄']])姓名 年龄
0 张三 22
1 李四 21
2 王五 19# 使用点符号(仅限列名是有效的Python标识符)
print(df.姓名)
5.2.选择行
# 通过标签选择
print(df.loc[0]) # 选择第一行# 通过位置选择
print(df.iloc[0]) # 选择第一行# 切片选择
print(df[0:2]) # 选择前两行特性 df.loc[] df.iloc[]
索引类型 标签索引(Label-based) 位置索引(Integer position-based)
包含端点 包含结束位置 不包含结束位置
语法 df.loc[row_label, col_label] df.iloc[row_position, col_position]
适用场景 已知标签时 已知位置时import pandas as pd
import numpy as np# 创建示例DataFrame
df = pd.DataFrame({'姓名': ['张三', '李四', '王五', '赵六'],'年龄': [25, 30, 35, 28],'城市': ['北京', '上海', '广州', '深圳'],'薪水': [5000, 8000, 6000, 7500]
}, index=['a', 'b', 'c', 'd']) # 自定义索引print(df)# 选择索引标签为 'a' 的行
row_a = df.loc['a']
print(row_a)# 选择多个标签的行
rows = df.loc[['a', 'c']]
print(rows)# 选择特定行和列
result = df.loc['b', '姓名'] # 选择b行的姓名列
print(result) # 输出: 李四# 选择多行多列
result = df.loc[['a', 'c'], ['姓名', '薪水']]
print(result)# 选择第0行(第一行)
row_0 = df.iloc[0]
print(row_0)# 选择第0行和第2行
rows = df.iloc[[0, 2]]
print(rows)# 选择第1行第0列
result = df.iloc[1, 0] # 第二行第一列
print(result) # 输出: 李四# 选择多行多列
result = df.iloc[[0, 2], [0, 3]] # 第0、2行,第0、3列
print(result)
5.3.条件过滤
# 选择年龄大于30的行
df[df['年龄'] > 30]# 多条件选择
df[(df['年龄'] > 25) & (df['城市'] == '北京')]# 使用 query 方法
df.query('年龄 > 25 and 城市 == "北京"')
6.数据处理与清洗
6.1.处理缺失值
# 检查缺失值
df.isnull()
df.isnull().sum()# 删除缺失值
df.dropna()# 填充缺失值
df.fillna(0) # 用0填充
df.fillna(df.mean()) # 用均值填充
df.fillna(method='ffill') # 用前一个值填充
6.2.数据类型转换
# 转换数据类型
df['年龄'] = df['年龄'].astype(float)# 转换为日期时间
df['日期'] = pd.to_datetime(df['日期列'])# 转换为分类数据
df['城市'] = df['城市'].astype('category')
6.3.重命名列
df.rename(columns={'旧列名': '新列名'}, inplace=True)
6.4.删除列和行
# 删除列
df.drop(['列名1', '列名2'], axis=1, inplace=True)# 删除行
df.drop([0, 1], axis=0, inplace=True) # 删除前两行
6.5.数据排序
# 按单列排序
df.sort_values('年龄', ascending=False)# 按多列排序
df.sort_values(['城市', '年龄'], ascending=[True, False])# 按索引排序
df.sort_index()
7.数据分组与聚合
7.1.分组操作
# 按城市分组
grouped = df.groupby('城市')# 查看分组
for city, group in grouped:print(city)print(group)# 聚合操作
df.groupby('城市')['年龄'].mean() # 每个城市的平均年龄
df.groupby('城市').agg({'年龄': 'mean', '薪水': 'sum'}) # 多个聚合
7.2.聚合函数
df.groupby('城市').agg({'年龄': ['mean', 'min', 'max', 'count'],'薪水': ['sum', 'mean', 'std']
})
8.数据合并与连接
8.1合并
# 连接两个 DataFrame
pd.concat([df1, df2], axis=0) # 纵向连接
pd.concat([df1, df2], axis=1) # 横向连接# 类似 SQL 的 JOIN
pd.merge(df1, df2, on='共同列', how='inner') # 内连接
pd.merge(df1, df2, on='共同列', how='left') # 左连接
9.时间序列处理
# 创建时间序列
dates = pd.date_range('20230101', periods=6)
ts = pd.Series(np.random.randn(6), index=dates)# 重采样
ts.resample('M').mean() # 按月重采样# 移动窗口操作
ts.rolling(window=3).mean() # 3期移动平均
10.数据可视化
import matplotlib.pyplot as plt# 简单的绘图
df['年龄'].plot(kind='hist', bins=20)
plt.show()df.plot(x='城市', y='年龄', kind='bar')
plt.show()# 更多绘图类型
df.plot.scatter(x='年龄', y='薪水')
df.plot.box()
11.安装
# 使用 pip
pip install pandas# 使用 conda
conda install pandas# 安装完整的数据科学套件
pip install pandas numpy matplotlib scikit-learn