Python Pandas
1.官网
https://pandas.pydata.org/docs/user_guide/10min.html
01.读写Excel:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 | import pandas as pd # 读取Excel帮助Link :https://pandas.pydata.org/docs/user_guide/io.html#excel-files file = 'student_excel.xlsx' # 1. 读取Excel单个Sheet df = pd.read_excel( file ) # 2. 查看数据头,数据尾,数据形状,数据类型 # df.head() / df.tail() / df.shape / df.dtypes # 2. 读取同一个Excel多个Sheet with pd.ExcelFile( file ) as excel: df1 = pd.read_excel(excel, "Sheet1" ) df2 = pd.read_excel(excel, "Sheet2" ) print (df1) # 3. 读取Excel的所有Sheet :sheet_name= None, sheet_name 默认为0读取第一个Sheet dfs = pd.read_excel( file , sheet_name = None ) for tdf in dfs.items(): print (tdf) # 4.读取指定的多个Sheet。Returns the 1st and 4th sheet, as a dictionary of DataFrames. pd.read_excel( file , sheet_name = [ "Sheet1" , 3 ]) output_file_path = 'Processed_Excel.xlsx' # 5.输出单个df到Excel文件 df.to_excel(output_file_path, sheet_name = "Sheet1" ) # 6.输出多个DF到Excel文件,mode='a'为追加 with pd.ExcelWriter(output_file_path, mode = 'w' ) as writer: df1.to_excel(writer, sheet_name = 'Sheet1' , index = False ) df2.to_excel(writer, sheet_name = 'Sheet2' , index = False ) |
02.读写数据库:
1 2 3 4 5 6 7 8 9 10 11 12 13 | import pandas as pd import sqlalchemy # 创建数据库连接引擎 engine = sqlalchemy.create_engine(f 'mysql+pymysql://{username}:{password}@{host}:{port}/{database}' , echo = True ) # 使用 pandas 读取数据 user_df = pd.read_sql( "SELECT * FROM user" , engine) print (user_df) # 移除自增字段列ID df_filtered = user_df.drop(columns = [ 'id' ]) # 将 DataFrame 写入 MySQL user_copy数据表中 (因为有自增字段id) df_filtered.to_sql( "user_copy" , con = engine, if_exists = 'append' , index = False ) |
03.数据结构Series:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 | import numpy as np import pandas as pd # 方式1 :直接创建Series,不指定索引 s1 = pd.Series([ 1 , 2 , 3 , 'xyz' , 5 ]) print (s1.index) # Series索引 print (s1.values) # Series 值 # 方式2 :指定Series的索引名称 s2 = pd.Series(np.random.randn( 5 ), index = [ "a" , "b" , "c" , "d" , "e" ]) print (s2) # 方式3 :使用字典创建Series s3 = pd.Series({ "a" : 1 , "b" : 2 , "c" : 3 , "d" : 4 , "e" : 5 }) # 查询Series数据 print (s3[ "a" ]) # 查询Series多个数据 print (s3[[ "a" , "b" , "c" ]]) # 使用索引查询Series数据 print (s3[s3 > 2 ]) # Series 切片1 print (s3[ 1 : 3 ]) # Series 切片2 eg:s.iloc[:3] print (s3.iloc[[ 4 , 3 , 1 ]]) # 查询Series的类型 or Series.dtype print ( type (s3[ "a" ])) # 创建Series, 整个列表值相同 s4 = pd.Series( 5.0 , index = [ "a" , "b" , "c" , "d" , "e" ]) print (s4) # 使用Series.get()方法时,缺少的标签将返回None或指定的默认值 data = s4.get( "f" , np.nan) print (data) # Series 可以直接计算 print (s3 + s4) |
04.数据结构DataFrame:
import numpy as np import pandas as pd dic_data = { "one": pd.Series([2, 2.0, 3.0], index=["a", "b", "c"]), "two": pd.Series([5, 6, 7, 8], index=["a", "b", "c", "d"]), } df = pd.DataFrame(dic_data) # 从字典中取部分值形成一个DataFrame df2 = pd.DataFrame(dic_data, index=["c", "b", "a"], columns=["one", "two", "new null column"]) print(df2) # 查询DataFrame的行索引和列索引,查看每列的类型 print(df2.index) / print(df2.columns) / print(df2.dtypes) # 使用DataFrame.from_dict构造一个按列索引的DataFrame,默认orient参数是'columns' df3 = pd.DataFrame.from_dict(dict([("column A", [1, 2, 3]), ("column B", [4, 5, 6])])) # 使用DataFrame.from_dict构造一个按行索引的DataFrame,orient="index"指定为行索引 df4 = pd.DataFrame.from_dict( dict([("row A", [1, 2, 3]), ("row B", [4, 5, 6])]), orient="index", columns=["column1", "column2", "column3"], ) # DataFrame的列选择 print(df2["one"]) # 01. DataFrame的列新增 ,df2 已改变 df2["three"] = df2["one"] * df2["two"] # 01.2. DataFrame的列新增 assign函数 ,df2为改变,结果在df5中 df5 = df2.assign(five=df2['one'] * df2['two']) print(df2["three"]) # 列删除 del df2["two"] 或者 three = df.2pop("three") three = df2.pop("three") # 删除列并返回被删除的列 df2["four"] = '整列常量' # 插入列 df2.insert(1, 'column3 name', three) # 选择行 df.loc[label] or df.iloc[loc] row3 = df2.iloc[2] row2 = df2.loc['b'] # 切片选 第二行和第三行 df_part_row = df2[1:3] # bool 选择满足条件的行 df_part_row2 = df2[df2['one'] < 3] # 随机数 生成大于uniform大于20.0,小于30.0 的10行4列的随机数 # (或np.random.randn函数生成随机符合正态分布的单个数,列表,多维数等) random_numbers = np.random.uniform(20.0, 30.0, (10, 4)) # DataFrame 行列转换 请访问T属性或DataFrame.transpose() print(df2.T)
04.Pandas查询数据的5种方法:
import pandas as pd from numpy import int32 df = pd.read_csv(r'tianqi.csv') # 可选:将某列设置为索引列 df.set_index('ymd', inplace=True) # 将表格所有行,bWendu移除℃字符,为int类型 df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('℃', '', ).astype(int32) print(df) # 01.查询单个值 loc[行索引,列索引] 得到一个值 df.loc['2018-07-01', 'bWendu'] # 02.查询多个值,得到一个Series df.loc['2018-07-01', ['bWendu', 'yWendu']] # 02.查询多行多列,得到一个DataFrame df.loc[['2018-07-01', '2018-07-02'], ['bWendu', 'yWendu']] # 03.查询区间的值 loc[起始行索引:结束行索引,列索引] df.loc['2018-07-01':'2018-07-10', ['bWendu', 'yWendu']] # 03.查询区间的值 loc[起始行索引:结束行索引,起始列索引:结束列索] df.loc['2018-07-01', 'bWendu':'fengxiang'] # 04.使用条件表达式进行查询 查询bWendu > 10的行 (列索引:表明设置为所有列) df.loc[df['bWendu'] > 10, :] # 04.使用条件表达式进行查询 进行多条件查询 df.loc[(df['bWendu'] > 10) & (df['tianqi'] == '晴'), :] # 05. 使用函数进行查询 df.loc[lambda tdf: (tdf['bWendu'] > 10) & (tdf['tianqi'] == '晴'), :] # 05. 使用自定义函数QueryData进行查询 def QueryData(df): return (df['bWendu'] > 10) & (df['tianqi'] == '晴') df.loc[QueryData, :]
import numpy as np import pandas as pd data = { 'A': [1, 2, 3, 4], 'B': [10, 20, -30, 40], 'C': [100, 200, 300, 400] } df = pd.DataFrame(data) # 使用 where 方法筛选列 A 中值大于 2 的行,不满足添加则将该位置的值置为0, 保留了一个和原DataFrame一样格式和数量的数据 filtered_df = df.where(df['A'] > 2, 0) # 使用 where 方法筛选单元格中值大于 1 的单元格,,不满足添加则将该位置的值置为单元格的相反数 filtered_df = df.where(df > 1, -df) # 对于不满足单元格大于0的值,将该单元格填充为该行A列的值 filtered_df = df.where(df > 0, df['A'], axis='index') # mask 函数和Where函数相反,对于满足条件的进行填充处理,不满足的不处理 masked_df = df.mask(df >= 0) # query 使用列名表达式进行查询,返回满足条件的数据 filtered_df = df.query('A < B and B < C') # query 索引列直接使用index关键字表示即可 filtered_df = df.query('index >= 1 and A < B ') df2 = pd.DataFrame({'a': ['one', 'one', 'two', 'two', 'two', 'three', 'four'], 'b': ['x', 'y', 'x', 'y', 'x', 'x', 'x'], 'c': np.random.randn(7)}) # 删除a列重复的行,重复行,只保留第一次出现的行 keep in [ first,last,False],keep=False表示只要重复则全部删除 df3 = df2.drop_duplicates(subset=['a'], keep='first') # 删除索引重复的行,只保留最后一个索引行 df2[~df2.index.duplicated(keep='last')] # 新增一个new_index,并重新设置索引 reset_df_names = df.reset_index(names='new_index')
05.Pandas新增数据列:
import pandas as pd from numpy import int32 df = pd.read_csv(r'tianqi.csv') # 01.直接赋值 修改列 df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('℃', '', ) df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('℃', '', ) df['bWendu'] = df['bWendu'].astype(int32) df['yWendu'] = df['yWendu'].astype(int32) # 01.直接赋值 新增列WenCha df.loc[:, 'WenCha'] = df['bWendu'] - df['yWendu'] # 02. DadaFrame.Apply() 方法 colume: axis=1 ,row: axis=0 df['WenCha'] = df.apply(lambda x: x['bWendu'] - x['yWendu'], axis=1) def GetTemperatureType(t) -> str: if t['bWendu'] > 33: return '高温' if t['yWendu'] < -10: return '低温' return '常温' df.loc[:, 'TemperatureType'] = df.apply(GetTemperatureType, axis=1) # 统计列中数值分别有多少个value_counts df.loc[:, 'TemperatureType'].value_counts() # 03.DadaFrame.assgin() 方法 ,同时赋值多个列,同时返回一个新的DadaFrame df2 df2 = df.assign( bWendu_huashi=lambda x: x['bWendu'] * 9 / 5 + 32, yWendu_huashi=lambda x: x['yWendu'] * 9 / 5 + 32 )
06.Pandas数据统计:
import pandas as pd from numpy import int32 df = pd.read_csv(r'tianqi.csv') df.loc[:, 'bWendu'] = df.loc[:, 'bWendu'].str.replace('℃', '', ) df.loc[:, 'yWendu'] = df.loc[:, 'yWendu'].str.replace('℃', '', ) df['bWendu'] = df['bWendu'].astype(int32) df['yWendu'] = df['yWendu'].astype(int32) print(df) # 汇总类统计 01.统计所有数字列的 数量 最大最小值 中位数 25% 75%分位数等 df.describe() # 汇总类统计 01.查看单个列的平均值 df['bWendu'].mean() #唯一去重 df['tianqi'].unique() #按值计数 df['fengli'].value_counts() #协方差 :衡量同向反向程度 df.cov() #相关系数:衡量相似度系数 df.corr()
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南