python使用pandas读xlsx文件的实现
作者:生活甜甜好运连连 时间:2021-01-21 05:00:10
使用pandas读xlsx文件
读取前n行数据
读取指定数据(指定行指定列)
获取文件行号和列标题
将数据转换为字典形式
import pandas as pd
#1.读取前n行所有数据
df1=pd.read_excel('d1.xlsx')#读取xlsx中的第一个sheet
data1=df1.head(10)#读取前10行所有数据
data2=df1.values#list【】 相当于一个矩阵,以行为单位
#data2=df.values() 报错:TypeError: 'numpy.ndarray' object is not callable
print("获取到所有的值:\n{0}".format(data1))#格式化输出
print("获取到所有的值:\n{0}".format(data2))
#2.读取特定行特定列
data3=df1.iloc[0].values#读取第一行所有数据
data4=df1.iloc[1,1]#读取指定行列位置数据:读取(1,1)位置的数据
data5=df1.iloc[[1,2]].values#读取指定多行:读取第一行和第二行所有数据
data6=df1.iloc[:,[0]].values#读取指定列的所有行数据:读取第一列所有数据
print("数据:\n{0}".format(data3))
print("数据:\n{0}".format(data4))
print("数据:\n{0}".format(data5))
print("数据:\n{0}".format(data6))
#3.获取xlsx文件行号、列号
print("输出行号列表{}".format(df1.index.values))#获取所有行的编号:0、1、2、3、4
print("输出列标题{}".format(df1.columns.values))#也就是每列的第一个元素
#4.将xlsx数据转换为字典
data=[]
for i in df1.index.values:#获取行号的索引,并对其遍历
#根据i来获取每一行指定的数据,并用to_dict转成字典
row_data=df1.loc[i,['id','name','class','data','score',]].to_dict()
data.append(row_data)
print("最终获取到的数据是:{0}".format(data))
#iloc和loc的区别:iloc根据行号来索引,loc根据index来索引。
#所以1,2,3应该用iloc,4应该有loc
数据:d1.xlsx
id | name | class | data | score |
201901 | A | 1 | Jan-20 | 1.3 |
201902 | B | 2 | Mar-20 | 3.4 |
201903 | C | 3 | May-20 | 3.4 |
201904 | D | 1 | Jan-20 | 3.4 |
201905 | E | 1 | Feb-20 | 5.6 |
201906 | F | 1 | Mar-20 | 4.6 |
201907 | G | 1 | Feb-19 | 7.8 |
201908 | H | 2 | Apr-30 | 5.6 |
201909 | I | 3 | Jan-42 | 5.6 |
201910 | G | 4 | Mar-30 | 4.5 |
201911 | K | 5 | Apr-20 | 3.4 |
201912 | L | 6 | Apr-20 | 2.3 |
201913 | M | 4 | Mar-20 | 2.4 |
运行结果展示
来源:https://blog.csdn.net/RitaAndWakaka/article/details/108366203
标签:python,pandas,xlsx
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
apache+mysql+php+ssl服务器之完全安装攻略
2023-11-16 07:34:16
pytest解读一次请求多个fixtures及多次请求
2023-07-20 01:13:43
在asp中通过vbs类实现rsa加密与解密
2010-05-27 12:18:00
php处理json格式数据经典案例总结
2023-11-21 13:54:42
使用python+whoosh实现全文检索
2021-01-04 05:29:46
Web开发者的百科全书——Google DocType
2008-07-03 13:06:00
中国传统色彩名录
2007-11-29 18:36:00
javascript面向对象编程(四)
2008-03-07 14:20:00
python中内置库os与sys模块的详细介绍
2021-12-05 21:30:33
![](https://img.aspxhome.com/file/2023/5/76835_0s.png)
JavaScript事件委托技术实例分析
2023-07-01 01:18:23
Python 去除字符串中指定字符串
2023-04-20 23:44:53
![](https://img.aspxhome.com/file/2023/2/70742_0s.png)
PHP共享内存使用与信号控制实例分析
2023-06-25 00:19:05
7个流行的Python强化学习算法及代码实现详解
2021-07-06 08:38:03
初学MySql5 所应了解的知识和常见问题
2009-03-06 17:49:00
SqlServer参数化查询之where in和like实现之xml和DataTable传参介绍
2012-05-22 18:38:49
Python 在 VSCode 中使用 IPython Kernel 的方法详解
2023-07-25 10:10:23
![](https://img.aspxhome.com/file/2023/7/72047_0s.png)
微信小程序实现图片轮播及文件上传
2023-09-05 00:12:52
Python实现鼠标自动在屏幕上随机移动功能
2022-01-30 05:08:15
游戏中的交互设计
2008-08-25 19:20:00
![](https://img.aspxhome.com/file/UploadPic/20088/25/2008825192344309s.jpg)
Python requests.post()方法中data和json参数的使用方法
2022-10-10 04:25:45