-
pandas中利用 .iloc 和 .loc 选取数据
Pandas 基本的数据结构是 Series(数组) 和 DataFrame(类似二维数组),Pandas 提供了 Index 对象,每个 Series 都会带有一个对应的Index,用来标记不同的元素,Index 的内容不一定是数字,也可以是字母、中文等,它类似于SQL中的主键
Pandas 读取文件时候,注意文件的存储路径不能带有中文,否则读取可能出错。
.iloc:根据标签的所在位置,从0开始计数,选取列
loc:根据DataFrame的具体标签选取列
import pandas as pd
filename ='../file/testiloc'
data = pd.read_excel(filename)
data_test1 = data.iloc[:,:8] #选取位置为[0,8)列的整列数据
data_test2 = data.iloc[0:2,8] #选取位置为8的列的[0,2)行的数据
data_test3 = data.loc[0:2,'工龄'] #选取列名为‘工龄’的[0,2]行的数据
# data.iloc[0:2,8] # ',' 前的部分标明选取的行,‘,’后的部分标明选取的列
# 数据集内容
>>>print(data_test1)
年龄 工龄 教育 工资 消费 饮食 购物 旅行
0 ...
1
2 ...
...
n ...
>>>print(data_test2)
交通
0 100
1 200
>>>print(data_test3)
工龄
0 10
1 11
2 15
-
drop函数的使用:删除行、删除列
drop函数默认删除行,列需要加axis = 1
print frame.drop(['a'])
print frame.drop(['Ohio'], axis = 1)
DataFrame.dropna(axis=0, how='any', thresh=None, subset=None, inplace=False)
axis:
axis=0: 删除包含缺失值的行
axis=1: 删除包含缺失值的列
how: 与axis配合使用
how=‘any’ :只要有缺失值出现,就删除该行货列
how=‘all’: 所有的值都缺失,才删除行或列
thresh: axis中至少有thresh个非缺失值,否则删除
比如 axis=0,thresh=10:标识如果该行中非缺失值的数量小于10,将删除改行
subset: list
在哪些列中查看是否有缺失值
inplace: 是否在原数据上操作。如果为真,返回None否则返回新的copy,去掉了缺失值。
- 数据分箱
import numpy as np
import pandas as pd
from pandas import DataFrame # 一般数据就都是二维的,不会是series了
score_list = np.random.randint(25, 100, size=20)
print(score_list)
df1 = DataFrame()
df1['Score'] = score_list
print(df1.head())
"""
Score
0 45
1 52
2 74
3 70
4 53
"""
# pd.util.testing.rands(3) for i in range(20)可以生成20个随机3位字符串
df1['Student'] = [pd.util.testing.rands(3) for i in range(20)]
print(df1.head())
"""
Score Student
0 85 Dqh
1 60 AaZ
2 50 O0R
3 71 8lk
4 62 Afd
5 26 Dsh
"""
# 指定一个分箱原则,规定:0-59为不及格,59-70为一般,70-80为良好,80-100位优秀
bins = [0,59,70,80,100]
# 利用pandas中的cut方法,指定分箱规则和对象,结果将获得一个Categories对象
print(pd.cut(df1['Score'],bins).head())
"""
0 (0, 59]
1 (80, 100]
2 (0, 59]
3 (0, 59]
4 (0, 59]
Name: Score, dtype: category
Categories (4, interval[int64]): [(0, 59] < (59, 70] < (70, 80] < (80, 100]]
"""
# 将这个对象作为新的一列加入df1中
df1['Categories'] = pd.cut(df1['Score'],bins)
print(df1.head())
"""
Score Student Categories
0 83 59q (80, 100]
1 95 Hau (80, 100]
2 62 jRj (59, 70]
3 76 c0r (70, 80]
4 60 WE4 (59, 70]
"""
# 指定label参数为每个区间赋一个标签
df1['Categories'] = pd.cut(df1['Score'],bins,labels=['low','ok','good','great'])
print(df1.head())
"""
Score Student Categories
0 30 xPe low
1 82 FpO great
2 94 NiV great
3 25 RMP low
4 47 R8F low
"""
- pandas.astype('category')
# 先创建一个简单的 DataFrame 实例
# 用一组数据记录各自的得分情况
import pandas as pd, numpy as np
players = ['Garsol','Hardon','Bill','Duran','James','Barter']
scores = [22,34,12,31,26,19]
teams = ['West','West','East','West','East','East']
df = pd.DataFrame({'player':players,'score':scores,'team':teams})
"""
print(df)
player score team
0 Garsol 22 West
1 Hardon 34 West
2 Bill 12 East
3 Duran 31 West
4 James 26 East
5 Barter 19 East
"""
# 可以看出 team 这一列,其实只有两种值:East 和 West,可以将 team 列的类型设定为 category
# 静态
df.team.astype('category')
# print(df.team.astype('category'))
"""
0 West
1 West
2 East
3 West
4 East
5 East
Name: team, dtype: category
Categories (2, object): [East, West]
# df.team 的变量类型变成了category
"""
df['which_team'] = df.team.astype('category')
print(df.which_team.values.value_counts()) # Here
# 动态
# print(pd.Series(scores))
# """
# 0 22
# 1 34
# 2 12
# 3 31
# 4 26
# 5 19
# """
"""
East 3
West 3
dtype: int64
"""
d = pd.Series(scores).describe()
score_ranges = [d['min']-1,d['mean'],d['max']+1]
# print(score_ranges) # [11.0, 24.0, 35.0]
score_labels = ['Role','Star']
# 用pd.cut(ori_data, bins, labels) 方法
# 以bins设定的画界点来将 ori_data 归类,然后用labels中对应的label来作为分类名
# 将高于平均分的划为 Star,低于平均分的划为 Role。
df['level'] = pd.cut(df['score'],score_ranges,labels=score_labels)
print('df :')
print(df)
"""
player score team level
0 Garsol 22 West Role
1 Hardon 34 West Star
2 Bill 12 East Role
3 Duran 31 West Star
4 James 26 East Star
5 Barter 19 East Role
"""
print('\n对比一下 Category 类型的数据和普通的 DataFrame中的列有什么区别')
print('\ndf[\'team\'] 是普通的 DataFrame列')
print(df['team'])
"""
df['team'] 是普通的 DataFrame列
0 West
1 West
2 East
3 West
4 East
5 East
Name: team, dtype: object
"""
print('\ndf[\'level\'] 是 Category 类型的')
print(df['level'])
"""
df['level'] 是 Category 类型的
0 Role
1 Star
2 Role
3 Star
4 Star
5 Role
Name: level, dtype: category
Categories (2, object): [Role < Star]
"""
print('\n可以看出 df[\'level\']有点像是集合,输出信息会去重后列出组成元素')
print(df['level'].get_values())
# ['Role' 'Star' 'Role' 'Star' 'Star' 'Role']