pandas中的另一种数据类型DataFrame
import pandas as pd
import numpy as np
1.创建DataFrame
pd.DataFrame(data=None, index=None, columns=None, dtype=None, copy=False)
data: 用来创建DataFrame的数据,可以是Series,字典,Numpy数组,DataFrame
index: 行索引。如果不指定,则默认采用数字索引,从0开始
columns:列名,列索引。如果不指定,则默认采用数字索引,从0开始
dtype: 数据类型
copy: 是否从输入中复制数据,默认为False,只有当data是DataFrame时起作用
用包含等长度列表或NumPy数组的字典
my_dict = {
'Teacher':['A','B','C'],
'Course':['Python','Java','C#'],
'Price':[4499,3999,3499]
}
df1 = pd.DataFrame(my_dict)
Teacher Course Price
0 A Python 4499
1 B Java 3999
2 C C# 3499
2.修改行索引
df2 = pd.DataFrame(my_dict,index=['一','二','三'])
Teacher Course Price
一 A Python 4499
二 B Java 3999
三 C C# 3499
3.修改列索引会导致值丢失
df3 = pd.DataFrame(my_dict,columns=['T','C','P'])
Empty DataFrame
Columns: [T, C, P]
Index: []
4.用numpy数组创建DataFrame
arr = np.arange(16).reshape(4,4)
df6 = pd.DataFrame(arr,index=list('abcd'),columns=list('ABCD'))
A B C D
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11
d 12 13 14 15
5.CSV文件读写
读取逗号间隔的CSV文件:pandas.read_csv()
常用参数:
·filepath_or_buffer:文件的路径,可以是本地文件也可以是文件的url
·sep: 指定的分割符,默认是英文逗号’,’
·header:指定行数用来作为列名,默认是第一行
·names:当header=None 时指定列名
·dtype:每列数据的类型
·encoding:编码格式,一般为 utf-8
读取文件
df_test = pd.read_excel(r'test.xls')
print(df_test)
A B C
0 one two three
1 4 NaN 6
2 seven NaN nine
指定列索引名称
df_test2 = pd.read_csv(r'test2.csv',header=None,names=['name','age','class'])
print(df_test2)
name age class
0 9.0 8.0 8.0
1 8.0 9.0 8.0
2 8.0 8.0 9.0
3 NaN NaN NaN
4 6.0 9.0 NaN
5 8.0 NaN NaN
6 NaN NaN 4.0
7 5.0 5.0 5.0
8 NaN 7.0 NaN
9 NaN 7.0 7.0
写入CSV文件
# 不生成行列索引
df1.to_csv('mycsv.csv',index=False,header=False)
6.访问和操作DataFrame
访问列
print(df_test['A'])
print('列的数据类型:',type(df_test['A']))
# 如果列名有空格还有中文,是不能用.的方式访问列
print(df_test.B)
# 访问多列 也不能用.方法
print(df_test[['A','C']])
0 one
1 4
2 seven
Name: A, dtype: object
列的数据类型: <class 'pandas.core.series.Series'>
0 two
1 NaN
2 NaN
Name: B, dtype: object
A C
0 one three
1 4 6
2 seven nine
增加列
# 赋值语句 直接在原数据上增加
df_test['D']=list('888')
print(df_test)
# 使用insert方法(插入第几列后,列名,列内容) 直接在原数据上增加
df_test.insert(2,column='b',value=list('666'))
print(df_test)
A B C D
0 one two three 8
1 4 NaN 6 8
2 seven NaN nine 8
A B b C D
0 one two 6 three 8
1 4 NaN 6 6 8
2 seven NaN 6 nine 8
删除行或列
# python自带del关键字
del(df_test['D'])
print(df_test)
# drop方法(列名,axis=0/1删除行还是列,inplace=True/False)
# inplace=True 表示直接在原数据上修改,不生成副本
df_test.drop('b',axis=1,inplace=True)
print(df_test)
A B b C
0 one two 6 three
1 4 NaN 6 6
2 seven NaN 6 nine
A B C
0 one two three
1 4 NaN 6
2 seven NaN nine
修改列
# 赋值语句
df_test['B']=list('012')
print(df_test)
df_test['B']=0
print(df_test)
A B C
0 one 0 three
1 4 1 6
2 seven 2 nine
A B C
0 one 0 three
1 4 0 6
2 seven 0 nine
访问行
使用属性loc和iloc来进行行的访问以及切片操作
loc支持索引和切片时使用默认的数值标签, index只能是整数
loc支持自定义的标签(行名,列名)
print(df_test.loc[0])
A one
B 0
C three
访问多行
df_test.iloc[[0,2]]
df_test.loc[[0,2]]
df_test.iloc[0,0]
df_test.loc[0,'A']
切片
逗号隔开,前面是行的索引或切片,后面是列的索引或切片
不能使用loc
print(df_test.iloc[:2,2:3])
C
0 three
1 6
布尔索引
print(df_test[df_test['B']>-1])
A B C
0 one 0 three
1 4 0 6
2 seven 0 nine
增加行
df_test.loc[3]=[8,0,10]
A B C
0 one 0 three
1 4 0 6
2 seven 0 nine
3 8 0 10
修改行
df_test.iloc[3] = [8,8,8]
df_test.loc[4]= [9,9,9]
A B C
0 one 0 three
1 4 0 6
2 seven 0 nine
3 8 8 8
4 9 9 9
设置和恢复索引
# 设置列索引 设置之后就不再是数据 生产副本
df_test.set_index('A',inplace=True)
# 恢复默认索引
df_test.reset_index()
- 7.DataFrame常见操作
# 查看前X行
print(df_test.head(2),'\n\n')
# 查看后X行
print(df_test.tail(1),'\n\n')
# 访问行的索引
print(df_test.index)
# 访问列的索引
print(df_test.columns,'\n\n')
# 访问值
print(df_test.values,'\n\n')
# 访问形状
print(df_test.shape)
# 访问信息
print(df_test.info)
# 统计有多少非空元素
print(df_test.count)
# 统计某一列有多少个不重复的值
print(df_test['A'].nunique())
# 显示某一列有哪些不重复的值
print(df_test['B'].unique())
# 对于数值型的列,描述其统计的内容
print(df_test.describe())
- 8.pandas直接抓取表格数据
url='http://s.askci.com/stock/a/?reportTime=2018-12-31&pageNum='
dfs=pd.read_html(url)
print(len(dfs))
dfs[1]
0 1 2 3
0 排名 股票代码 企业简称 净利润(亿元)
1 1 601398 工商银行 2987.23
2 2 601939 建设银行 2556.26
3 3 601288 农业银行 2026.31
4 4 601988 中国银行 1924.35
5 5 601318 中国平安 1204.52
6 6 600036 招商银行 808.19
7 7 600028 中国石化 802.89
8 8 601328 交通银行 741.65
9 9 601857 中国石油 724.1
10 10 601166 兴业银行 606.20