Pandas 是Python的核心数据分析支持库,用来分析数据的。
目录
数据结构
pandas中的数据结构
- Series:一维数组
- Dataframe:二维数组
- Panel:三维的数组,可以理解为
DataFrame
的容器
Series
是带有标签的一维数组,可以保存任何数据类型
创建
1. 由字典创建
import pandas as pd
dic = {'a':1 ,'b':2 , 'c':3, '4':4, '5':5}
s = pd.Series(dic)
print(s)
2. 由数组创建(一维数组)
import numpy as np
import pandas as pd
arr = np.random.randn(5) # 随机数组
s = pd.Series(arr)
print(s)
可自定义索引标签和value的类型
第一个参数默认是data,其他的注意要写参数名
s = pd.Series(arr, index = ['a','b','c','d','e'],dtype = object)
3. 由标量(常数)创建
s = pd.Series(10, index = range(4))
print(s)
名称属性
就是可以给Series取个名字,通过.name也可以访问到
import numpy as np
import pandas as pd
s = pd.Series(np.random.randn(5),name = 'test')
print(s)
s2 = s.rename('hehehe')
print(s2)
索引
series具有一维数组的性质,同时又可以设置标签等其他属性
可作为索引的主要有这些:
以位置下标
标签(index属性)
切片
布尔型索引
位置下标:
默认的标签
s = pd.Series(np.random.rand(5))
print(s)
print(s[0],type(s[0]),s[0].dtype)
标签索引:
s = pd.Series(np.random.rand(5), index = ['a','b','c','d','e'])
print(s)
print(s['a'],type(s['a']),s['a'].dtype)
sci = s[['a','b','e']] # 传入标签列表
print(sci,type(sci))
这里出入的标签列表,如果没有设置标签的话,也可以使用下标列表
切片引用:
用index做切片是末端包含
s2= pd.Series(np.random.rand(5), index = ['a','b','c','d','e'])
print(s2[0:3],s2[3])
print(s2[:-1])
print(s2['a':'c'],s2['c']) # 使用index,包含c
结果
a 0.158454
b 0.038400
c 0.694389
dtype: float64 0.31275209878130783
a 0.618478
b 0.788997
c 0.907406
d 0.266732
dtype: float64
a 0.618478
b 0.788997
c 0.907406
dtype: float64 0.9074060218801755
布尔型索引:
传入bool索引,可以传入一个条件表达式,也可以传入对应的bool数组
对series数组进行条件判断,返回新的bool数组
s = pd.Series(np.random.rand(3)*100)
s[4] = None # 添加一个空值
print(s)
series对象如下
0 66.085980
1 24.802260
2 14.667315
4 NaN
dtype: float64
对s数组进行条件判断,生成新的bool数组
bs1 = s > 50 # s中满足>50条件的为true
bs2 = s.isnull() # 为空为true
bs3 = s.notnull() # b不为空的为true
print(s[s > 50])
print(s[bs3])
# 输出
0 50.696955
2 73.003087
dtype: float64
0 50.696955
1 13.602553
2 73.003087
dtype: float64
基本技巧
基本操作技巧包括数据查看、重新索引、对齐、添加、修改和删除值
查看:
s = pd.Series(np.random.rand(50))
print(s.head(10))
print(s.tail()) # 默认为5条
重新索引:
s = pd.Series(np.random.rand(3), index = ['a','b','c'])
s1 = s.reindex(['c','b','a','d']) # 缺失值的值为NaN
s2 = s.reindex(['c','b','a','d'], fill_value = 0) # 填充缺失值的值
print(s1)
print(s2)
对齐:自动对齐,两个series相加,空值和任何值计算结果仍为空值
s1 = pd.Series(np.random.rand(3), index = ['Jack','Marry','Tom'])
s2 = pd.Series(np.random.rand(3), index = ['Wang','Jack','Marry'])
print(s1+s2)
# 结果
Jack 0.972090
Marry 1.008601
Tom NaN
Wang NaN
dtype: float64
删除,添加,修改:
通过索引直接删除,添加和修改。append可以添加数组
s1 = s.drop('n')
s2 = s.drop(['g', 'j'])
s3[5] = 100
s4['a'] = 100
s5 = s1.append(s2)
s[['b','c']] = 200
Dataframe
带有标签的二维数组。Dataframe带有index(行标签)和columns(列标签)。
创建
一维就只用care一个轴就行了,二维的有行和列两个维度,也可理解成x轴和y轴。具备这两个属性的基本上就满足条件了
数组 /list / Series 组成的字典创建
列是字典的key,行是数组的索引
import numpy as np
import pandas as pd
data1 = {'name':['Jack','Tom','Mary'],
'age':[18,19,20],
'gender':['m','m','w']}
data2 = {'one':pd.Series(np.random.rand(2), index = ['a','b']),
'two':pd.Series(np.random.rand(3),index = ['a','b','c'])}
df1 = pd.DataFrame(data1)
df2 = pd.DataFrame(data2)
print(df1)
print(df2)
# 结果
name age gender
0 Jack 18 m
1 Tom 19 m
2 Mary 20 w
one two
a 0.640279 0.347906
b 0.144437 0.866770
c NaN 0.316864
通过二维数组直接创建
df1 = pd.DataFrame(ar) # 默认行标和列标
df2 = pd.DataFrame(ar, index = ['a', 'b', 'c'], columns = ['one','two','three'])
由字典组成的列表创建
这里注意,字典的key依然是column,行标可以自己设置index,默认为数组下标
由字典组成的字典创建
columns为字典的key,index为子字典的key,这里index不能修改
索引
Dataframe对象df
df = pd.DataFrame(np.random.rand(12).reshape(3,4)*100,
index = ['one','two','three'],
columns = ['a','b','c','d'])
df[列名],df[[列名,列名]],df[:1]
df.loc[ ]根据index选行,df.iloc[ ]根据整数选航
操作
增删改查
这里多了个转置
print(df.head(2))
print(df.tail()) # 默认5条
print(df.T)
# .T 转置
修改值
df['e'] = 20 # 整列操作
df[['a','c']] = 100 # 许多列同时操作
print(df)
删除 del / drop()
del删除列,drop删除行
del df['a'] # 删除列
print(df)
print(df.drop(0)) # 删除行
print(df.drop([1,2]))
排序
按值排序.sort_values,ascending = True升序,false降序
索引排序 .sort_index
print(df1.sort_values(['a'], ascending = True)) # 升序
print(df1.sort_values(['a'], ascending = False)) # 降序
去重
from pandas import DataFrame
df = DataFrame({'k1': ['one'] * 3 + ['two'] * 4, 'k2': [1, 1, 2, 3, 3, 4, 4]})
print(df)
结果:
k1 k2
0 one 1
1 one 1
2 one 2
3 two 3
4 two 3
5 two 4
6 two 4
duplicated():返回一个布尔型Series
,表示各行是否是重复行
print(df.duplicated())
----------
0 False
1 True
2 False
3 False
4 True
5 False
6 True
dtype: bool
drop_duplicates():用于去除重复的行数
print(df.drop_duplicates())
----------
k1 k2
0 one 1
2 one 2
3 two 3
5 two 4