Python-pandas-基础入门

📅 2026/8/3 12:49:13
Python-pandas-基础入门
Pandas 基础入门 什么是 PandasPandas 是 Python 最重要的数据分析库名字源自 “Panel Data”面板数据。它提供了两个核心数据结构结构类比维度说明SeriesExcel 的一列1 维带标签的一维数组DataFrameExcel 的一张表2 维带行列标签的二维表格 安装与导入pipinstallpandasimportpandasaspdimportnumpyasnp# 检查版本print(pd.__version__) Series — 一维带标签数组创建 Series# 从列表创建spd.Series([10,20,30,40])print(s)# 0 10# 1 20# 2 30# 3 40# dtype: int64# 自定义索引spd.Series([10,20,30,40],index[a,b,c,d])print(s)# a 10# b 20# c 30# d 40# 从字典创建spd.Series({北京:2154,上海:2487,广州:1868,深圳:1756})print(s[北京])# 2154# 从标量创建广播spd.Series(5,index[a,b,c])# 所有值都是 5# 指定数据类型spd.Series([1,2,3],dtypefloat64)Series 基本属性spd.Series([10,20,30,40],index[a,b,c,d])print(s.values)# [10 20 30 40] (numpy array)print(s.index)# Index([a, b, c, d])print(s.dtype)# int64print(s.shape)# (4,)print(s.size)# 4print(s.name)# None可设置 s.name valueSeries 基本操作# 取值print(s[0])# 按位置: 10print(s[a])# 按标签: 10print(s[:3])# 切片# 运算自动对齐索引s1pd.Series([1,2,3],index[a,b,c])s2pd.Series([10,20,30],index[b,c,d])print(s1s2)# a NaN ← a 只在 s1 中# b 12.0 ← 2 10# c 23.0 ← 3 20# d NaN ← d 只在 s2 中# 统计print(s.mean())# 均值print(s.std())# 标准差print(s.min())# 最小值print(s.max())# 最大值print(s.median())# 中位数print(s.sum())# 求和 DataFrame — 二维表格 ⭐创建 DataFrame# 方式一: 从字典创建最常用dfpd.DataFrame({姓名:[张三,李四,王五,赵六],年龄:[22,25,30,28],城市:[北京,上海,广州,深圳],工资:[8000,12000,15000,10000]})print(df)# 方式二: 从列表嵌套列表data[[张三,22,北京,8000],[李四,25,上海,12000],[王五,30,广州,15000],[赵六,28,深圳,10000]]dfpd.DataFrame(data,columns[姓名,年龄,城市,工资])# 方式三: 从 NumPy 数组arrnp.random.randn(5,3)dfpd.DataFrame(arr,columns[A,B,C])# 方式四: 从字典列表JSON 风格records[{name:张三,age:22},{name:李四,age:25},{name:王五,age:30}]dfpd.DataFrame(records)DataFrame 基本属性dfpd.DataFrame({A:[1,2,3],B:[4.0,5.5,6.2],C:[x,y,z]})print(df.shape)# (3, 3) 行数, 列数print(df.columns)# Index([A, B, C])print(df.index)# RangeIndex(start0, stop3, step1)print(df.dtypes)# 每列的数据类型print(df.values)# 转为 numpy arrayprint(df.size)# 总元素数print(df.ndim)# 维度数2数据预览dfpd.read_csv(data.csv)# 假设有个大文件df.head()# 前 5 行默认df.head(10)# 前 10 行df.tail()# 后 5 行df.sample(5)# 随机 5 行df.info()# 列名、非空计数、数据类型、内存占用df.describe()# 数值列的统计摘要count/mean/std/min/25%/50%/75%/max# 针对非数值列df.describe(includeobject)# count/unique/top/freqdf.describe(includeall)# 所有列的统计 读写文件CSV 文件 ⭐# 读取 CSVdfpd.read_csv(data.csv)# 基本读取dfpd.read_csv(data.csv,sep;)# 分隔符dfpd.read_csv(data.csv,encodinggbk)# 中文编码dfpd.read_csv(data.csv,headerNone)# 无表头dfpd.read_csv(data.csv,names[A,B])# 自定义列名dfpd.read_csv(data.csv,index_col0)# 指定索引列dfpd.read_csv(data.csv,usecols[A,B])# 只读指定列dfpd.read_csv(data.csv,nrows100)# 只读前 100 行dfpd.read_csv(data.csv,skiprows5)# 跳过前 5 行dfpd.read_csv(data.csv,na_values[NA,?,])# 指定缺失值# 写入 CSVdf.to_csv(output.csv,indexFalse)# 不保存行索引df.to_csv(output.csv,encodingutf-8-sig)# 中文兼容 ExcelExcel 文件# 读取 Exceldfpd.read_excel(data.xlsx)# 默认 Sheet1dfpd.read_excel(data.xlsx,sheet_nameSheet2)# 指定 Sheetdfpd.read_excel(data.xlsx,sheet_nameNone)# 读取所有 Sheet返回 dict# 写入 Exceldf.to_excel(output.xlsx,sheet_name数据,indexFalse)# 写入多个 Sheetwithpd.ExcelWriter(output.xlsx)aswriter:df1.to_excel(writer,sheet_nameSheet1,indexFalse)df2.to_excel(writer,sheet_nameSheet2,indexFalse)其他格式# JSONdfpd.read_json(data.json)df.to_json(output.json,orientrecords,force_asciiFalse)# SQLfromsqlalchemyimportcreate_engine enginecreate_engine(sqlite:///database.db)dfpd.read_sql(SELECT * FROM table_name,engine)df.to_sql(table_name,engine,if_existsreplace,indexFalse)# HTML 表格tablespd.read_html(https://example.com/table-page.html)dftables[0]# 页面上第一个表格# Clipboard直接从剪贴板粘贴dfpd.read_clipboard() 快速上手示例importpandasaspdimportnumpyasnp# 1. 创建一份销售数据dfpd.DataFrame({日期:pd.date_range(2024-01-01,periods12,freqME),销售额:np.random.randint(100,500,12),客户数:np.random.randint(10,50,12),城市:[北京,上海,广州,深圳]*3})# 2. 快速查看print(df.head())print(df.info())print(df.describe())print(f数据形状:{df.shape})print(f列名:{df.columns.tolist()})# 3. 简单分析print(f总销售额:{df[销售额].sum()})print(f月均销售额:{df[销售额].mean():.1f})print(f最高销售额:{df[销售额].max()})print(f各城市出现次数:\n{df[城市].value_counts()})# 4. 保存结果df.to_csv(sales_2024.csv,indexFalse,encodingutf-8-sig)[[pandas2-总览|← 返回总览]]