网站在手机上内页图不显示,网站建设基本流程图,中国工程建设信息网站,宁波做网站定制接着上篇《Python库学习(十一):数据分析Pandas[上篇]》,继续学习Pandas 1.数据过滤 在数据处理中#xff0c;我们经常会对数据进行过滤#xff0c;为此Pandas中提供mask()和where()两个函数#xff1b; mask(): 在 满足条件的情况下替换数据#xff0c;而不满足条件的部分… 接着上篇《Python库学习(十一):数据分析Pandas[上篇]》,继续学习Pandas 1.数据过滤 在数据处理中我们经常会对数据进行过滤为此Pandas中提供mask()和where()两个函数 mask(): 在 满足条件的情况下替换数据而不满足条件的部分则保留原始数据 where(): 在 不满足条件的情况下替换数据而满足条件的部分则保留原始数据; from datetime import datetime, timedeltaimport randomimport pandas as pddef getDate() - str: 用来生成日期 :return: # 随机减去天数 tmp datetime.now() - timedelta(daysrandom.randint(1, 100)) # 格式化时间 return tmp.strftime(%Y-%m-%d)if __name__ __main__: # 准备数据 水果 fruits [苹果, 香蕉, 橘子, 榴莲, 葡萄] rows 3 today datetime.now() data_dict { fruit: [random.choice(fruits) for _ in range(rows)], date: [getDate() for _ in range(rows)], price: [round(random.uniform(1, 5), 2) for _ in range(rows)], # 随机生成售价,并保留两位小数 } data pd.DataFrame(data_dict) # 复制数据方便后续演示 data_tmp data.copy() print(-------------- 生成数据预览 ------------------) print(data) print(-------------- 普通条件:列出价格大于3.0的水果 ------------------) condition data[price] 3.0 # 列出价格大于3.0的水果 fruit_res data[condition][fruit] print(价格大于3.0的水果:, fruit_res.to_numpy()) print(-------------- 使用mask:把价格大于3.0设置成0元 ------------------) # 把价格大于3.0设置成0元 data[price] data[price].mask(data[price] 3.0, other0) print(data) print(-------------- 使用where:把价格不大于3.0设置成0元 ------------------) # 把价格不大于3.0设置成0元 data_tmp[price] data_tmp[price].where(data_tmp[price] 3.0, other0) print(data_tmp) -------------- 生成数据预览 ------------------ fruit date price0 橘子 2023-10-16 3.521 苹果 2023-09-08 1.072 葡萄 2023-09-27 2.69-------------- 普通条件:列出价格大于3.0的水果 ------------------价格大于3.0的水果: [橘子]-------------- 使用mask:把价格大于3.0设置成0元 ------------------ fruit date price0 橘子 2023-10-16 0.001 苹果 2023-09-08 1.072 葡萄 2023-09-27 2.69-------------- 使用where:把价格不大于3.0设置成0元 ------------------ fruit date price0 橘子 2023-10-16 3.521 苹果 2023-09-08 0.002 葡萄 2023-09-27 0.00 注:从功能上可以看出,mask()和where()是正好两个相反的函数 2. 数据遍历 if __name__ __main__: # 数据生成参考上面 print(-------------- 生成数据预览 ------------------) print(data) print(-------------- 遍历dataframe数据 ------------------) for index, row in data.iterrows(): print(index:{} 水果:{} 日期:{} 售价:{}.format(index, row[fruit], row[date], row[price])) print(-------------- 遍历Series数据 ------------------) series_data pd.Series({name: 张三, age: 20, height: 185}) for k, v in series_data.items(): print(key:{} value:{}.format(k, v))-------------- 生成数据预览 ------------------ fruit date price0 橘子 2023-10-14 3.711 橘子 2023-10-03 3.742 香蕉 2023-09-06 1.173 葡萄 2023-08-30 1.164 榴莲 2023-10-21 1.47-------------- 遍历dataframe数据 ------------------index:0 水果:橘子 日期:2023-10-14 售价:3.71index:1 水果:橘子 日期:2023-10-03 售价:3.74index:2 水果:香蕉 日期:2023-09-06 售价:1.17index:3 水果:葡萄 日期:2023-08-30 售价:1.16index:4 水果:榴莲 日期:2023-10-21 售价:1.47-------------- 遍历Series数据 ------------------key:name value:张三key:age value:20key:height value:185 3. 分层索引 分层索引MultiIndex是Pandas 中一种允许在一个轴上拥有多个两个或更多级别的索引方式。这种索引方式适用于多维数据和具有多个层次结构的数据。 3.1 使用set_index from datetime import datetime, timedeltaimport randomimport pandas as pdif __name__ __main__: # 创建一个示例 DataFrame fruits [苹果, 苹果, 橘子, 橘子, 橘子, 百香果] rows len(fruits) today datetime.now() dict_var { fruit: fruits, date: [(today - timedelta(daysi)).strftime(%Y-%m-%d) for i in range(rows)], price: [round(random.uniform(1, 5), 2) for _ in range(rows)], num: [round(random.uniform(10, 500), 2) for _ in range(rows)] } sale_data pd.DataFrame(dict_var) # 设置多层次索引 sale_data.set_index([fruit, date], inplaceTrue) print(----------------------------- 创建多层次索引-----------------------------------) print(sale_data) print(----------------------------- 打印索引信息-----------------------------------) index_info sale_data.index print(index_info) print(----------------------------- 使用loc 访问多层次索引-----------------------------------) search_price sale_data.loc[(苹果, 2023-11-02), price] print(search_price) print(----------------------------- 使用xs 访问多层次索引-----------------------------------) search_xs sale_data.xs(key(苹果, 2023-11-02), level[fruit, date]) print(search_xs) ----------------------------- 创建多层次索引----------------------------------- price numfruit date 苹果 2023-11-02 1.08 211.31 2023-11-01 1.35 308.87橘子 2023-10-31 3.25 180.84 2023-10-30 2.53 115.14 2023-10-29 2.61 146.49百香果 2023-10-28 1.36 246.01----------------------------- 打印索引信息-----------------------------------MultiIndex([( 苹果, 2023-11-02), ( 苹果, 2023-11-01), ( 橘子, 2023-10-31), ( 橘子, 2023-10-30), ( 橘子, 2023-10-29), (百香果, 2023-10-28)], names[fruit, date])----------------------------- 使用loc 访问多层次索引-----------------------------------1.08----------------------------- 使用xs 访问多层次索引----------------------------------- price numfruit date 苹果 2023-11-02 1.08 211.31 3.2 使用**MultiIndex** if __name__ __main__: fruits [苹果, 香蕉, 橘子, 榴莲, 葡萄, 雪花梨, 百香果] date_list [2023-03-11, 2023-03-13, 2023-03-15] cols pd.MultiIndex.from_product([date_list, [售卖价, 成交量]], names[日期, 水果]) list_var [] for i in range(len(fruits)): tmp [ round(random.uniform(1, 5), 2), round(random.uniform(1, 100), 2), round(random.uniform(1, 5), 2), round(random.uniform(1, 100), 2), round(random.uniform(1, 5), 2), round(random.uniform(1, 100), 2), ] list_var.append(tmp) print(--------------------------------创建多层次索引--------------------------------) multi_data pd.DataFrame(list_var, indexfruits, columnscols) print(multi_data) print(--------------------------------打印多层次索引--------------------------------) print(multi_data.index) print(multi_data.columns) # 搜行 print(----------------------------- 使用filter-- 行搜索-----------------------------------) print(multi_data.filter(like苹果, axis0)) print(----------------------------- 使用filter-- 列搜索-----------------------------------) # 搜列 print(multi_data.filter(like2023-03-11, axis1)) --------------------------------创建多层次索引--------------------------------日期 2023-03-11 2023-03-13 2023-03-15 水果 售卖价 成交量 售卖价 成交量 售卖价 成交量苹果 2.54 69.40 3.27 18.89 1.93 3.37香蕉 1.99 53.33 1.88 92.77 3.64 26.60橘子 2.48 27.81 3.20 8.71 2.58 85.44榴莲 3.15 47.89 1.09 93.15 2.51 85.30葡萄 4.59 35.58 4.88 77.02 3.08 64.96雪花梨 3.17 9.58 4.48 44.17 4.15 88.94百香果 3.05 7.65 3.51 82.03 3.97 52.06--------------------------------打印多层次索引--------------------------------Index([苹果, 香蕉, 橘子, 榴莲, 葡萄, 雪花梨, 百香果], dtypeobject)MultiIndex([(2023-03-11, 售卖价), (2023-03-11, 成交量), (2023-03-13, 售卖价), (2023-03-13, 成交量), (2023-03-15, 售卖价), (2023-03-15, 成交量)], names[日期, 水果])----------------------------- 使用filter-- 行搜索-----------------------------------日期 2023-03-11 2023-03-13 2023-03-15 水果 售卖价 成交量 售卖价 成交量 售卖价 成交量苹果 2.54 69.4 3.27 18.89 1.93 3.37----------------------------- 使用filter-- 列搜索-----------------------------------日期 2023-03-11 水果 售卖价 成交量苹果 2.54 69.40香蕉 1.99 53.33橘子 2.48 27.81榴莲 3.15 47.89葡萄 4.59 35.58雪花梨 3.17 9.58百香果 3.05 7.65 4. 数据读写 4.1 写入表格 from datetime import datetime, timedeltaimport randomimport pandas as pdif __name__ __main__: fruits [苹果, 香蕉, 橘子, 榴莲, 葡萄, 雪花梨, 百香果] rows 20 today datetime.now() print(today.strftime(%Y-%m-%d %H:%M:%S.%f)[:-3]) dict_var { 水果: [random.choice(fruits) for _ in range(rows)], 进价: [round(random.uniform(1, 5), 4) for _ in range(rows)], 售价: [round(random.uniform(1, 5), 4) for _ in range(rows)], 日期: [(today - timedelta(daysi)).strftime(%Y-%m-%d) for i in range(rows)], 销量: [round(random.uniform(10, 500), 4) for _ in range(rows)] } sale_data pd.DataFrame(dict_var) print(sale_data) # 保存,浮点数保留两位小数 sale_data.to_excel(./test.xlsx, float_format%.2f) a.主要参数说明: excel_writer: Excel 文件名或 ExcelWriter 对象。如果是文件名将创建一个 ExcelWriter 对象并在退出时自动关闭文件。 sheet_name: 字符串工作表的名称默认为 Sheet1。 na_rep: 用于表示缺失值的字符串默认为空字符串。 float_format: 用于设置浮点数列的数据格式。默认为 None表示使用 Excel 默认的格式当设置 %.2f表示保留两位。 columns: 要写入的列的列表默认为 None。如果设置为 None将写入所有列如果指定列名列表将只写入指定的列。 header: 是否包含列名默认为 True。如果设置为 False将不写入列名。 index: 是否包含行索引默认为 True。如果设置为 False将不写入行索引。 index_label: 用于指定行索引列的名称。默认为 None。 startrow: 数据写入的起始行默认为 0。 startcol: 数据写入的起始列默认为 0。 freeze_panes: 值是一个元组用于指定要冻结的行和列的位置。例如 (2, 3) 表示冻结第 2 行和第 3 列。默认为 None表示不冻结任何行或列。 4.2 读取表格 import pandas as pdif __name__ __main__: # ------------------------------ 读取表格 ---------------------------------- print(----------------------------- 读取全部数据 -----------------------) # 读取全部数据 read_all_data pd.read_excel(./test.xlsx) print(read_all_data) print(----------------------------- 只读取第1、2列数据 -----------------------) # 只读取第1、2列数据 read_column_data pd.read_excel(./test.xlsx, usecols[1, 2]) print(read_column_data) print(----------------------------- 只读取列名为:日期、销量 的数据 -----------------------) # 读取 read_column_data2 pd.read_excel(./test.xlsx, usecols[日期, 销量]) print(read_column_data2)----------------------------- 读取全部数据 ----------------------- Unnamed: 0 水果 进价 售价 日期 销量0 0 榴莲 3.74 2.35 2023-11-03 217.031 1 百香果 2.08 3.64 2023-11-02 311.402 2 百香果 2.17 4.94 2023-11-01 404.553 3 橘子 2.41 2.71 2023-10-31 431.204 4 葡萄 2.78 3.99 2023-10-30 323.015 5 苹果 4.79 1.68 2023-10-29 161.266 6 百香果 1.61 2.78 2023-10-28 407.277 7 榴莲 1.56 4.08 2023-10-27 44.748 8 雪花梨 1.60 3.02 2023-10-26 119.139 9 葡萄 3.03 1.08 2023-10-25 152.87----------------------------- 只读取第1、2列数据 ----------------------- 水果 进价0 榴莲 3.741 百香果 2.082 百香果 2.173 橘子 2.414 葡萄 2.785 苹果 4.796 百香果 1.617 榴莲 1.568 雪花梨 1.609 葡萄 3.03----------------------------- 只读取列名为:日期、销量 的数据 ----------------------- 日期 销量0 2023-11-03 217.031 2023-11-02 311.402 2023-11-01 404.553 2023-10-31 431.204 2023-10-30 323.015 2023-10-29 161.266 2023-10-28 407.277 2023-10-27 44.748 2023-10-26 119.139 2023-10-25 152.87 主要参数说明 io: 文件路径、 ExcelWriter 对象或者类似文件对象的路径/对象。 sheet_name: 表示要读取的工作表的名称或索引。默认为 0表示读取第一个工作表。 header: 用作列名的行的行号。默认为 0表示使用第一行作为列名。 names: 覆盖 header 的结果即指定列名。 index_col: 用作行索引的列的列号或列名。 usecols: 要读取的列的列表可以是列名或列的索引。 4.3 更多方法 除了上面的表格读取还有更多类型的读取方式,方法简单整理如下: 图来自 5.数据可视化 Pandas底层对Matplotlib进行了封装所以可以直接使用Matplotlib的绘图方法 5.1 折线图 from datetime import datetime, timedeltaimport randomimport pandas as pdfrom matplotlib import pyplot as plt# 设置字体以便正确显示中文plt.rcParams[font.sans-serif] [FangSong]# 正确显示连字符plt.rcParams[axes.unicode_minus] Falseif __name__ __main__: # ------------------------------ 生成数据 ---------------------------------- rows 30 beginDate datetime(2023, 4, 10) print(beginDate:, beginDate.strftime(%Y-%m-%d)) dict_var { 日期: [(beginDate timedelta(daysi)).strftime(%Y-%m-%d) for i in range(rows)], 进价: [round(random.uniform(1, 4), 2) for _ in range(rows)], 售价: [round(random.uniform(2, 6), 2) for _ in range(rows)], } apple_data pd.DataFrame(dict_var) apple_data.plot(x日期, y[进价, 售价], title苹果销售数据) plt.show() 5.2 散点图 from datetime import datetime, timedeltaimport randomimport numpy as npimport pandas as pdfrom matplotlib import pyplot as plt# 设置字体以便正确显示中文plt.rcParams[font.sans-serif] [FangSong]# 正确显示连字符plt.rcParams[axes.unicode_minus] Falseif __name__ __main__: # ------------------------------ 生成数据 ---------------------------------- rows 30 beginDate datetime(2023, 4, 1) print(beginDate:, beginDate.strftime(%Y-%m-%d)) dict_var { 日期: [(beginDate timedelta(daysi)).strftime(%d) for i in range(rows)], 进价: [round(random.uniform(1, 4), 2) for _ in range(rows)], 售价: [round(random.uniform(2, 10), 2) for _ in range(rows)], 销量: [round(random.uniform(10, 500), 4) for _ in range(rows)] } apple_data pd.DataFrame(dict_var) # 设置颜色 colorList 10 * np.random.rand(rows) # 设置 apple_data.plot(x日期, y售价, kindscatter, title苹果销售数据, colorcolorList, sdict_var[销量]) plt.show() color:表示的是颜色可以使用字符串表示颜色名称也可以使用十六进制颜色码。 s: 散点图特有的属性表示散点大小。 5.3 柱形图 import randomimport pandas as pdfrom matplotlib import pyplot as plt# 设置字体以便正确显示中文plt.rcParams[font.sans-serif] [FangSong]# 正确显示连字符plt.rcParams[axes.unicode_minus] Falseif __name__ __main__: # ------------------------------ 生成数据 ---------------------------------- fruits [苹果, 香蕉, 橘子, 榴莲, 葡萄, 雪花梨, 百香果] rows 7 beginDate datetime(2023, 4, 1) print(beginDate:, beginDate.strftime(%Y-%m-%d)) dict_var { 水果: [苹果, 香蕉, 橘子, 榴莲, 葡萄, 雪花梨, 百香果], 销量: [round(random.uniform(10, 1000), 2) for _ in range(rows)] } apple_data pd.DataFrame(dict_var) apple_data.plot(x水果, y销量, kindbar, title水果销售数据) plt.show() 本文由 mdnice 多平台发布