Pandas 基于NumPy,为数据清理提供捷径
数据结构
序列Series,类似于numpy中的一维数组,不过Series带索引
数据框DataFrame,类似于Numpy中的二维数组
Series
创建series两种方式
series = pd.Series([1,2,3,4],index=['a','b','c','d']) # index缺省时候,就是一维数组了print(series)
dic = {'zhangsan':18,'lisi':20}
series2 = pd.Series(dic)print(series2)DataFrame
dic = { 'name': ['zhangsan', 'lisi', 'ww'], 'age': [20, 18, 21], 'gender': ['m', 'f', 'm']
}
data = pd.DataFrame(dic, columns=['name', 'age', 'gender'], index=['1', '2', '3'])
print(data)"""
name age gender
1 zhangsan 20 m
2 lisi 18 f
3 ww 21 m
"""基本属性
| 函数 | 返回值 |
|---|---|
| values | 元素 |
| index | 索引 |
| columns | 列名 |
| ndim | 维度数 |
| shape | 数据形状,行列数目 |
| dtypes | 类型 |
| size | 元素个数 |
增删改查
查
dic = { 'name': ['zhangsan', 'lisi', 'ww'], 'age': [20, 18, 21], 'gender': ['m', 'f', 'm']
}
data = pd.DataFrame(dic, columns=['name', 'age', 'gender'], index=['1', '2', '3'])print(data[['name', 'age']]['1': '2'])#%%
name age
1 zhangsan 20
2 lisi 18#%%# DataFrame.loc[行索引名称或条件,列索引名称]# DataFrame.iloc[行索引位置,列索引位置]print(data.loc['1':'2','name':'gender'])print(data.iloc[:2,0:3])#%%
name age gender
1 zhangsan 20 m
2 lisi 18 f
name age gender
1 zhangsan 20 m
2 lisi 18 f#%%# loc,iloc 访问方式可以传入表达式,返回满足表达式的所有值print(data.loc[data['age']>18,['name','age']])#%%
name age
1 zhangsan 20
3 ww 21#%%更改DataFrame中的数据
data['age'] = 20 data.loc[:,'age'] = 20 data.iloc[:,1] = 20# 使用series赋值val = pd.Series([20,20,20], index = '1,2,3') data['age'] = val
添加数据
data['class'] = '1604'
删除数据
data.drop('class', axis=1,inplace=True) # 删除class 列数据,并对源数据生效# axis = 0 ,删除列# inplace = false ,对原数据不生效索引重建
series.reindex(['a','b','c'])data.reindex(['0','1','2'])
读写数据
读取数据库
文本读取
read_table(), read_csv()Excel
read_excel
作者:Rengao
链接:https://www.jianshu.com/p/49f3245de8f3
随时随地看视频