Pandas数据类型-DataFrame之创建和访问
DataFrame是一个表格型(类似Excel)的数据结构,它既有行,也有列,每一行的索引为index,每一列的索引为column。
同样也可以把DataFrame类型看作是一维的,由同样行索引的一组数据组成。
DataFrame的创建
创建空的DataFrame
import pandas as pd
pd.DataFrame(columns={"a":"","b":"","c":""},index=[0])
通过字典创建
- key为列名,字典的value就是一个Serise.values,即为一列数据
dict1 = {"name":["Jim", "Lucy", "HanMeimei", "Lili"], "age":[11, 12, 13, 14], "score":[90, 100, 80, 70]}
pd.DataFrame(dict1)
| name | age | score |
---|
0 | Jim | 11 | 90 |
---|
1 | Lucy | 12 | 100 |
---|
2 | HanMeimei | 13 | 80 |
---|
3 | Lili | 14 | 70 |
---|
直接用list的数据创建DataFrame
- 一个二维列表,注意列表中的每一个列表元素为一行数据
df1 = pd.DataFrame([[1, 2, 3],["a", "b", "c"], ["a1", "b2", "c3"]], index=["第一行", "第二行", "第三行"],
columns=["第一列", "第二列", "第三列"])
print(df1)
第一列 第二列 第三列
第一行 1 2 3
第二行 a b c
第三行 a1 b2 c3
读取csv或者excel文件为DataFrame格式
df1 = pd.read_excel(r".\study\test_excel.xlsx", sheet_name="student")
print("df1---------------\n", df1, type(df1))
df1---------------
name age sex address score
0 刘一 18 女 上海 100
1 花二 40 男 上海 99
2 张三 25 男 北京 80
3 李四 30 男 西安 40
4 王五 70 男 青岛 70
5 孙六 65 女 泰州 90 <class 'pandas.core.frame.DataFrame'>
用numpy的矩阵创建dataframe
import numpy as np
array = np.random.rand(2,3)
df1 = pd.DataFrame(array,columns=['first','second','third'])
print(df1)
first second third
0 0.671161 0.319496 0.998158
1 0.372354 0.456053 0.945547
查看DataFrame数据属性
df.head()
array = np.random.rand(8,3)
df1 = pd.DataFrame(array,columns=['first','second','third'])
print(df1.head(3))
first second third
0 0.414661 0.576802 0.733472
1 0.304392 0.706122 0.367632
2 0.737718 0.700953 0.710541
查看数据后几行
df1.tail()
| first | second | third |
---|
3 | 0.680279 | 0.653830 | 0.120031 |
---|
4 | 0.124661 | 0.803662 | 0.411242 |
---|
5 | 0.018145 | 0.492444 | 0.738249 |
---|
6 | 0.871111 | 0.483860 | 0.381885 |
---|
7 | 0.719817 | 0.961853 | 0.526238 |
---|
重置索引
- df.reset_index, 重置索引,添加新的索引0-n
- df.set_index, 重置索引,设置某一列为新的索引
print(df1.reset_index())
print(df1.set_index("第0列"))
index 第0列 第1列 第2列
0 第0行 0.938223 0.450784 0.958613
1 第1行 0.005883 0.433231 0.654217
2 第2行 0.729364 0.424220 0.960798
3 第3行 0.829794 0.090153 0.134994
4 第4行 0.391034 0.001752 0.626693
5 第5行 0.975350 0.318862 0.626255
6 第6行 0.400560 0.815432 0.417564
7 第7行 0.359789 0.565618 0.130726
第1列 第2列
第0列
0.938223 0.450784 0.958613
0.005883 0.433231 0.654217
0.729364 0.424220 0.960798
0.829794 0.090153 0.134994
0.391034 0.001752 0.626693
0.975350 0.318862 0.626255
0.400560 0.815432 0.417564
0.359789 0.565618 0.130726
查看下标
- df.index, df.columns
- 当需要修改时,必须统一修改,不能单个修改
df1.index = ["第"+ str(i) +"行" for i in range(8)]
df1.columns = ["第"+ str(i) +"列" for i in range(3)]
print(df1.index)
print(df1.columns)
Index(['第0行', '第1行', '第2行', '第3行', '第4行', '第5行', '第6行', '第7行'], dtype='object')
Index(['第0列', '第1列', '第2列'], dtype='object')
查看下标
- df.index, df.columns
- 当需要修改时,必须统一修改,不能单个修改
查看数据值
df1.values
array([[0.38875075, 0.43803462, 0.12459244],
[0.56419024, 0.75568682, 0.13764671],
[0.80400939, 0.79626389, 0.66016963],
[0.31140927, 0.76798005, 0.21945531],
[0.14646588, 0.92297446, 0.7054672 ],
[0.66496854, 0.30049814, 0.54736761],
[0.07047599, 0.47393679, 0.2407982 ],
[0.5220982 , 0.61223117, 0.68845914]])
查看数据特性
- df.dtypes
- df.shape
- df.ndim
- df.size
- df.axes
print(df1.dtypes)
print(df1.shape)
print(df1.ndim)
print(df1.size)
print(df1.axes)
first float64
second float64
third float64
dtype: object
(8, 3)
2
24
[RangeIndex(start=0, stop=8, step=1), Index(['first', 'second', 'third'], dtype='object')]
单独计算某列的统计值
- df1[‘first’].sum() #求和
- df1[‘first’].mean() #求平均数
- df1[‘first’].count() #求数量
- df1[‘first’].max()
- df1[‘first’].min()
DataFrame元素的访问
索引单个cell
使用at,iat
- 通过元素的行和列索引对来访问单个cell,at 和 iat 属性只能访问单个cell,区别是at可以使用字符串和整数,而iat只能使用整数。
at 和 iat 的格式是:[row, column]。
df1 = pd.read_excel(r".\study\test_excel.xlsx", sheet_name="student")
print("df1---------------\n", df1, type(df1))
df1---------------
name age sex address score
0 刘一 18 女 上海 100
1 花二 40 男 上海 99
2 张三 25 男 北京 80
3 李四 30 男 西安 40
4 王五 70 男 青岛 70
5 孙六 65 女 泰州 90 <class 'pandas.core.frame.DataFrame'>
print(df1.at[3, "age"])
print(df1.iat[3, 0])
print(df1.loc[3, 'age'])
30
李四
30
使用属性和索引方式
print(df1.name[2])
print(df1["name"][4])
张三
王五
使用loc,iloc
- df.loc和iloc主要是根据DataFrame的行标和列标进行数据的筛选的,通过行列名称或者索引进行访问行或者列,都可以只传入单个值,实现精确匹配
print(df1.loc[2, "name"])
张三
访问多个元素
- loc 和 iloc 属性可以访问多个cell,区别是loc可以使用标签和布尔(掩码)数组,不能使用整数位置(整数代表元素的位置),
而iloc只能使用整数位置。
通过属性方式访问列
- 通过属性方式只能访问单独的列,返回series对象。
- 对于列索引数组方式,一次访问多列。返回的对象是DataFrame类型。
df1 = pd.read_excel(r".\study\test_excel.xlsx", sheet_name="student")
print("df1---------------\n", df1["age"])
print("df1---------------\n", df1.age)
print(df[['name','age']])
df1---------------
0 18
1 40
2 25
3 30
4 70
5 65
Name: age, dtype: int64
df1---------------
0 18
1 40
2 25
3 30
4 70
5 65
Name: age, dtype: int64
name age
0 刘一 18
1 花二 40
2 张三 25
3 李四 30
4 王五 70
5 孙六 65
访问单行,包括所有列
df1 = pd.read_csv(r".\study\weather.txt")
df1.set_index('ymd', inplace=True)
df1.loc["2018-01-03"]
bWendu 2℃
yWendu -5℃
tianqi 多云
fengxiang 北风
fengli 1-2级
aqi 28
aqiInfo 优
aqiLevel 1
Name: 2018-01-03, dtype: object
通过loc和iloc多方式访问
[row, column]方式
- [row, column]访问由row和column 确定的元素
- 行列标签任意可以是列表或者一个范围
df1 = pd.read_csv(r".\study\weather.txt")
df1.set_index('ymd', inplace=True)
print(df1.loc[['2018-01-03','2018-01-04','2018-01-08'], 'bWendu'])
print(df1.loc[['2018-01-03','2018-01-04','2018-01-05'], ['bWendu', 'yWendu']])
df2 = df1.loc['2018-01-03':'2018-01-05', 'bWendu':'fengxiang']
print("df2-----------\n", df2)
df1.loc["2018-01-03"]
ymd
2018-01-03 2℃
2018-01-04 0℃
2018-01-08 2℃
Name: bWendu, dtype: object
bWendu yWendu
ymd
2018-01-03 2℃ -5℃
2018-01-04 0℃ -8℃
2018-01-05 3℃ -6℃
df2-----------
bWendu yWendu tianqi fengxiang
ymd
2018-01-03 2℃ -5℃ 多云 北风
2018-01-04 0℃ -8℃ 阴 东北风
2018-01-05 3℃ -6℃ 多云~晴 西北风
bWendu 2℃
yWendu -5℃
tianqi 多云
fengxiang 北风
fengli 1-2级
aqi 28
aqiInfo 优
aqiLevel 1
Name: 2018-01-03, dtype: object
布尔列表,访问行
df2.loc[[True, False, True]]
| bWendu | yWendu | tianqi | fengxiang |
---|
ymd | | | | |
---|
2018-01-03 | 2℃ | -5℃ | 多云 | 北风 |
---|
2018-01-05 | 3℃ | -6℃ | 多云~晴 | 西北风 |
---|
条件筛选
- 可以是条件表达式,得到一个布尔列表。序列具有矢量化操作的特性,当选择某一列时,可以通过逻辑运算得出布尔索引数组
- 当条件表达式组合时,注意每一个都需要有括号, 通过逻辑运算符连接起来
df1 = pd.read_excel(r".\study\test_excel.xlsx", sheet_name="student")
print("df1---------------\n", df1, type(df1))
print((df1["age"]>50) & (df1["score"]<80))
df1.loc[(df1["age"]>50) & (df1["score"]<80), :]
df1---------------
name age sex address score
0 刘一 18 女 上海 100
1 花二 40 男 上海 99
2 张三 25 男 北京 80
3 李四 30 男 西安 40
4 王五 70 男 青岛 70
5 孙六 65 女 泰州 90 <class 'pandas.core.frame.DataFrame'>
0 False
1 False
2 False
3 False
4 True
5 False
dtype: bool
| name | age | sex | address | score |
---|
4 | 王五 | 70 | 男 | 青岛 | 70 |
---|
利用函数查询
df1.loc[lambda df1: (df1["age"]<50) & (df1["score"]<80), :]
| name | age | sex | address | score |
---|
3 | 李四 | 30 | 男 | 西安 | 40 |
---|
df1 = pd.read_csv(r".\study\weather.txt")
df1.set_index('ymd', inplace=True)
def query_my_data(df):
return df.index.str.startswith("2018-09")& df1["aqiLevel"]==1
df1.loc[query_my_data,:].head(5)
| bWendu | yWendu | tianqi | fengxiang | fengli | aqi | aqiInfo | aqiLevel |
---|
ymd | | | | | | | | |
---|
2018-09-01 | 27℃ | 19℃ | 阴~小雨 | 南风 | 1-2级 | 50 | 优 | 1 |
---|
2018-09-04 | 31℃ | 18℃ | 晴 | 西南风 | 3-4级 | 24 | 优 | 1 |
---|
2018-09-05 | 31℃ | 19℃ | 晴~多云 | 西南风 | 3-4级 | 34 | 优 | 1 |
---|
2018-09-06 | 27℃ | 18℃ | 多云~晴 | 西北风 | 4-5级 | 37 | 优 | 1 |
---|
2018-09-07 | 27℃ | 16℃ | 晴 | 西北风 | 3-4级 | 22 | 优 | 1 |
---|