一、pandas中Excel文件常见操作
- 基本语法
# import导入模块
import pandas as pd
import numpy as np
# 读取文件,在这里我读取的是本地文件,也可以直接传入绝对路径
s1 = pd.read_excel('./meal_order_detail.xlsx')
s2 = pd.read_excel('C:\Users\Administrator\Documents\Tencent Files\1661157270\FileRecv\meal_order_detail.xlsx')
- 参数分析
(1)sheetname: 切换sheet表格
# 1、可以传入整型,表示从0开始的索引
# 2、可以传入表的名称
# 3、可以传入None,表示一次性获取所有表格
# 4、可以传入list,['sheetname', 2], 索引和表格连用
s1 = pd.read_excel('./meal_order_detail.xlsx', sheet_name=0) # 指定获取某一张表
s2 = pd.read_excel('./meal_order_detail.xlsx', sheet_name=[0, 1,2]) # 列表传参,获取表的内容
s3 = pd.read_excel('./meal_order_detail.xlsx', sheet_name=None) # 传入None,返回全部的表
(2)keys() 查看表的名称
data_name = data.keys()
print(data_name)
dict_keys(['meal_order_detail1', 'meal_order_detail2', 'meal_order_detail3'])
(3)header 参数
# 表示选择哪一行作为索引,默认为第一行,
# 当header不为0时,会将默认为列索引之前的行全部删掉
# 当文件没有设置表头时,需要将header设置为None, 并且传入与列的数量一致的list
data = pd.read_excel('./meal_order_detail.xlsx', header=None, names=['rank','rank','rank','rank','player','club','goal','common_goal','penalty'])
(4) skiprows 跳过哪些行
# 跳过哪些行,是在读取的过程中,不去获取这些行
# 对指定行跳过之后,再重新将第一行作为表头
# 如果跳的有第一行,那么跳过后,就使用了第二行作为表头
data3 = pd.read_excel('./meal_order_detail.xlsx', skiprows=[0, 1])
(5)head: 取前五行
print(data.head) # 取前五行
2958 417 609957 NA NA.1 ... 0.1 NA.6 NA.7 caipu/202003.jpg 1442
0 2961 417 609950 NaN NaN ... 0 NaN NaN caipu/303001.jpg 1442
1 2966 417 610038 NaN NaN ... 0 NaN NaN caipu/105002.jpg 1442
2 2968 417 610003 NaN NaN ... 0 NaN NaN caipu/503002.jpg 1442
3 1899 301 610019 NaN NaN ... 0 NaN NaN caipu/204002.jpg 1095
4 1902 301 609991 NaN NaN ... 0 NaN NaN caipu/201001.jpg 1095
[5 rows x 19 columns]
(6)tail: 取后五行
print(data.tail) # 取后五行
2958 417 609957 NA NA.1 ... 0.1 NA.6 NA.7 caipu/202003.jpg 1442
2772 6750 774 610011 NaN NaN ... 0 NaN NaN caipu/601005.jpg 1138
2773 6742 774 609996 NaN NaN ... 0 NaN NaN caipu/201006.jpg 1138
2774 6756 774 609949 NaN NaN ... 0 NaN NaN caipu/404005.jpg 1138
2775 6763 774 610014 NaN NaN ... 0 NaN NaN caipu/302003.jpg 1138
2776 6764 774 610017 NaN NaN ... 0 NaN NaN caipu/302006.jpg 1138
[5 rows x 19 columns]
二、pandas中csv文件常见操作
- csv 属于文本文件,逗号分隔符文件,编码一般为gbk
基本语法
# 基本语法
data = pd.read_csv(r'F:\数据分析\第七天\meal_order_info.csv', sep=',', encoding='gbk', engine='python')
info_id emp_id number_consumers ... order_status phone name
0 417 1442 4 ... 1 18688880641 苗宇怡
1 301 1095 3 ... 1 18688880174 赵颖
2 413 1147 6 ... 1 18688880276 徐毅凡
3 415 1166 4 ... 1 18688880231 张大鹏
4 392 1094 10 ... 1 18688880173 孙熙凯
.. ... ... ... ... ... ... ...
940 641 1095 8 ... 1 18688880307 李靖
941 672 1089 6 ... 1 18688880305 莫言
942 692 1155 8 ... 1 18688880327 习一冰
943 647 1094 4 ... 1 18688880207 章春华
944 570 1113 8 ... 1 18688880313 唐雅嘉
[945 rows x 21 columns]
- 参数分析
(1)sep元素分隔符, csv文件中默认分隔符为逗号
(2)encoding读取文件使用的编码格式
(3)engine: 底层编译方式,默认为C语言,如果是遇到编码问题,可以尝试将engine改为pytho - 、保存文件
# 基本语法
data1.to_excel('11.xlsx')