Python里的这个Pandas库是第三方库,需要自己安装。
pip install pandas
还有依赖库:
pip install xlrd
pip install xlwt
Pandas包含了NumPy,pytz等库,功能比较的强大。
---------------------------------------------------------------------------------------------------------------------------
好的进入正题。
Pandas可以这样操作:
【1】标配的代码:
#coding=utf-8
import pandas as pd
df=pd.read_excel("文件路径",sheet_name="工作表名",headers=0)
行接下来需要读取一下,这里就可以直接用head语句。
c=df.head(1000)
有时候程序会出现读取不完整情况,需要添加这几行代码:
pd.set_option("display.max_rows",1000)
pd.set_option("display.max_columns",1000)
pd.set_option("display.unicode.east_asian_width",True)
让读取范围最大化。
如果现在想查询内容的话,则需要把变量c【见前文】变成一个字典。
c=dict(c)
然后现在有三种方式查询某一列:
【1】
直接用索引
get=c["列标题"]
print(get)
【2】
用顺序,这里就可能会稍微复杂一点
get=c[c.keys()[列的顺序号,例如:0]]
print(get)
【3】
这种就更复杂了:
比如,要查询A列的话:
find_str="A"
num=0
for i in find_str:
num+=ord(i.upper())-65
get=c[c.keys()[num]]
print(get)
明白了吗?
给你们看一下效果(这里用的是我自己的工作表)
>>>c=df.head(1000)
>>>c=dict(c)
>>>print(c)
{'var1': 0 1
1 -3
2 3
3 4
4 0
5 -4
6 7
7 1
8 2
9 2
10 4
11 5
Name: var1, dtype: int64, 'var2': 0 239471
1 7622221
2 -63333
3 -44567
4 -1567
5 3456781
6 82334
7 12345
8 13454
9 123454
10 324
11 3224546
Name: var2, dtype: int64, 'var3': 0 1
1 2
2 3
3 2
4 5
5 3
6 9
7 -2
8 2
9 -3
10 4
11 5
Name: var3, dtype: int64, 'sum': 0 3
1 0
2 0
3 2
4 -5
5 0
6 24
7 0
8 5
9 0
10 17
11 0
Name: sum, dtype: int64}
>>>print(c['var1'])
0 1
1 -3
2 3
3 4
4 0
5 -4
6 7
7 1
8 2
9 2
10 4
11 5
Name: var1, dtype: int64
就挺好。
接下来,我们可以获取这一列中x行的信息:【接着上文继续编,变量get用那三种方法的结果是一样的】
get=dict(get)
print(get[1])#这里的1是键不是索引
输出的是-3,就是var1列中的第2行。
行关于Excel的读取就到这里了,谢谢阅读-------------------------------------------------------------------------