官方文档:https://pandas.pydata.org/docs/
安装
pip install pandas
jupyter notebook安装
! pip install pandas
数据结构
Pandas最重要的数据结构:Series、DataFrame
Series
类似一维数组,由一组数据(Numpy数据类型)及一组与之对应的索引(数据标签)组成
构建
import numpy as np
import pandas as pd
ser_obj = pd.Series(range(10, 20))
print(ser_obj)
0 10
1 11
2 12
3 13
4 14
5 15
6 16
7 17
8 18
9 19
dtype: int64
获取数据
print(ser_obj.values)
[10 11 12 13 14 15 16 17 18 19]
获取索引
print(ser_obj.index)
RangeIndex(start=0, stop=10, step=1)
运算
print(ser_obj*2)
0 20
1 22
2 24
3 26
4 28
5 30
6 32
7 34
8 36
9 38
dtype: int64
print(ser_obj>15)
0 False
1 False
2 False
3 False
4 False
5 False
6 True
7 True
8 True
9 True
dtype: bool
使用字典构建
year_data = {
2001: 17.8, 2005: 20.1, 2003: 16.5}
ser_obj2 = pd.Series(year_data)
print(ser_obj2)
print(ser_obj2.index)
print(ser_obj2[2001])
2001 17.8
2005 20.1
2003 16.5
dtype: float64
Int64Index([2001, 2005, 2003], dtype=‘int64’)
17.8
name属性
对象名:ser_obj.name
对象索引名:ser_obj.index.name
print(ser_obj2.name)
print(ser_obj2.index.name)
None
None
ser_obj2.name = 'temp'
ser_obj2.index.name = 'year'
print(ser_obj2.head())
year
2001 17.8
2005 20.1
2003 16.5
Name: temp, dtype: float64
series对象本质上由两个数组构成,一个数组构成对象的键,一个数组构成对象的值
DataFrame
表格型数据结构,每列可以是不同类型的值,既有行索引也有列索引
行索引:index,0轴
列索引:columns,1轴
构建
t = pd.DataFrame(np.arange(12).reshape(3,4))
print(t)
t1 = pd.DataFrame(np.random.randn(5,4))
print(t1)
print(t1.head())
dict_data = {
'A':1,
'B':pd.Timestamp('20210831'),
'C':pd.Series(1,index=list(range(4)),dtype='float32'),
'D':np.array([3]*4,dtype='int32'),
'E':['python','java','c++','c'],
'F':'hello'}
t2 = pd.DataFrame(dict_data)
print(t2)
print(t2['A'])
0 1
1 1
2 1
3 1
Name: A, dtype: int64
print(type(t2['A'])
<class ‘pandas.core.series.Series’>
print(t2.A)
0 1
1 1
2 1
3 1
Name: A, dtype: int64
d1 = [{
"name" : "xiaohong" ,"age" :32,"tel" :10010},{
"name": "xiaogang" ,"tel": 10000} ,{
"name":"xiaowang" ,"age":22}]
t3 = pd.DataFrame(d1)
t3
增加列
t2['G'] = t2['D']+4
t2
删除列
# 1
del(t2['G'])
# 2
t2.drop_duplicates(subset=['G'])
t2
- subset:默认采用所有列,可以指定特定列
- keep:可选{‘first’, ‘last’, False}, 默认 ‘first’,选择保留第一次还是最后一次行,或者都不要
- inplace:bool, 默认 False, 判断是原地替换还是返回一个copy
- ignore_index:bool, 默认 False,如果设置为True,索引会重新从0开始
索引
print(type(t2.index))
print(t2.index)
<class ‘pandas.core.indexes.numeric.Int64Index’>
Int64Index([0, 1, 2, 3], dtype=‘int64’)
索引对象不可变,保证数据安全。
常见索引:
- Index 索引
- Int64Index 整数索引
- MultiIndex 层级索引
- DatetimeIndex 时间戳索引
指定行索引名
s = pd.Series(range(5),index=['a','b','c','d','e'])
s
a 0
b 1
c 2
d 3
e 4
dtype: int64
print(s