pandas模块主要用于进行数据探索和数据分析。
(1)导入
import pandas as pda
#之后即可在代码中用pda代替pandas,省事
(2)创建数据:
Series:表示一串数字,代表一行一列 ,用index表示其索引。
DataFrame:数据框,类似表格,代表行列整合的数据,用columns表示其表头。
1)以数组形式创建:
#通过数组方式创建数据
a=pda.Series([8,9,2,1])
b=pda.Series([8,9,2,1],index=["a","b","c","d"])
c=pda.DataFrame([[5,8,9,6],[3,5,7,9],[33,54,58,10],[2,12,55,78]])
d=pda.DataFrame([[5,8,9,6],[3,5,7,9],[33,54,58,10],[2,12,55,78]],columns=["one","two","three","four"])
结果:
>>> a
0 8
1 9
2 2
3 1
dtype: int64
>>> b
a 8
b 9
c 2
d 1
dtype: int64
>>> c
0 1 2 3
0 5 8 9 6
1 3 5 7 9
2 33 54 58 10
3 2 12 55 78
>>> d
one two three four
0 5 8 9 6
1 3 5 7 9
2 33 54 58 10
3 2 12 55 78
2)以数组形式创建:
#通过字典的方式创建数据框
e=pda.DataFrame({
"one":4,
"two":[3,2,1],
"three":list(str(982)),
})
若数据参差不齐会自动填充,结果如下:
>>> e
one three two
0 4 9 3
1 4 8 2
2 4 2 1
(3)获取数据:
f=d.head()#头部数据,默认前五行
g=d.head(1)#从头部输出特定行
h=d.tail()#尾部数据,默认后五行
i=d.tail(2)#从尾部输出特定行
结果:
>>> f
one two three four
0 5 8 9 6
1 3 5 7 9
2 33 54 58 10
3 2 12 55 78
>>> g
one two three four
0 5 8 9 6
>>> h
one two three four
0 5 8 9 6
1 3 5 7 9
2 33 54 58 10
3 2 12 55 78
>>> i
one two three four
2 33 54 58 10
3 2 12 55 78
(4)数据统计:
扫描二维码关注公众号,回复:
3755376 查看本文章
d.describe()
结果:
>>> d.describe()
one two three four
count 4.000000 4.000000 4.00000 4.000000
mean 10.750000 19.750000 32.25000 25.750000
std 14.885675 23.012678 28.04015 34.874776
min 2.000000 5.000000 7.00000 6.000000
25% 2.750000 7.250000 8.50000 8.250000
50% 4.000000 10.000000 32.00000 9.500000
75% 12.000000 22.500000 55.75000 27.000000
max 33.000000 54.000000 58.00000 78.000000
从上至下分别代表:元素数量、平均值、标准差、最小值、25%分位数、50%分位数、75%分位数,最大值。
(5)转置(行列位置颠倒)
d=pda.DataFrame([[5,8,9,6],[3,5,7,9],[33,54,58,10],[2,12,55,78]],columns=["one","two","three","four"])
j=d.T
结果:
>>> d.T
0 1 2 3
one 5 3 33 2
two 8 5 54 12
three 9 7 58 55
four 6 9 10 78
(6)数据导入:
1)导入CSV格式数据:
#数据导入
i=pda.read_csv("E:/hexun.csv")
可对导入的数据进行统计以及按列排序:
#统计
i.describe()
#排序
i.sort_values(by="21") #21是列名
2)导入Excel格式数据:
#excel
j=pda.read_excel("E:/abc.xls")
3)导入数据框ql数据(以mysql以及sqlite为例):
#mysql
import pymysql
conn=pymysql.connect(host="127.0.0.1",user="root",db="hexun")
sql="select * from myhexun"
k=pda.read_sql(sql,conn)
#sqlite
import sqlite3
conn = sqlite3.connect('E:/dangdang.db')
sql="select * from house"
k=pda.read_sql(sql,conn)
4)导入html中的表格数据:
以某网页为例:
提取该网页的表格数据代码:
#html中的表格信息
l=pda.read_html("http://www.nseac.com/html/234/680687.html")
4)导入txt文本数据(注意文件要使用UTF-8编码):
#导入文本
n=pda.read_table("E:/a.txt")