pandas含有使数据分析工作变得更快更简单的高级数据结构和操作工具,pandas是基于Numpy构建的。pandas在过去的几年中逐渐成长为一个非常强大的库。
引入pandas
import numpy as np
import pandas as pd
因此,一般在代码中看到pd.,都指的是pandas
pandas的数据结构介绍
pandas有两个主要的数据结构:Series和DataFrame.Series
Series是一种类似于一维数组的对象,它由一组数据(各种Numpy数据类型)以及一组与之相关的数据标签(即索引)组成。
Series的字符串表现形式为:索引在左边,值在右边。你可以通过Series的values和index属性获取其数组表现形式和索引对象:
Series创建后会自动生成索引,默认从0开始,
创建Series
obj2 = pd.Series([4,7,-5,3],index=['d','b','a','c'])
obj2
Out[99]:
d 4
b 7
a -5
c 3
dtype: int64
方法二:通过字典创建
a = {'a':1,'b':2,'c':3}
b = pd.Series(a)
b
Out[102]:
a 1
b 2
c 3
dtype: int64
查询
通过索引查单值
In [172]: series_4['a']
Out[172]: 4
通过索引序列查多值:
series_4[['a','b']]
Out[174]:
a 4
b 2
dtype: int64
通过布尔类型索引筛选:
In [175]: series_4[series_4>2]
Out[175]:
a 4
c 3
dtype: int64
通过位置切片和标签切片查询数据:
series_4
Out[194]:
a 4
b 2
c 3
dtype: int64
series_4[:2]
Out[195]:
a 4
b 2
dtype: int64
series_4['a':'c']
Out[196]:
a 4
b 2
c 3
dtype: int64
删除
注意删除的是索引值
b
Out[105]:
a 1
b 2
c 3
dtype: int64
b.drop('a')
Out[106]:
b 2
c 3
dtype: int64
值的修改方法
s1
Out[112]:
a 1
b 2
c 3
dtype: int64
s1['a'] ='测试'
s1
Out[114]:
a 测试
b 2
c 3
dtype: object
索引修改方法
s1
Out[80]:
ceshi 1
001 3
002 5
003 6
004 8
dtype: int6
s1.index._values[0] = '测试'
s1
Out[87]:
测试 1
001 3
002 5
003 6
004 8
dtype: int64
值修改方法
#打印S1
s1
Out[94]:
0 1.0
1 3.0
2 5.0
3 NaN
4 6.0
5 8.0
dtype: float64
#将索引值为0的值重新赋值
s1[0] = 11111
s1
Out[96]:
0 11111.0
1 3.0
2 5.0
3 NaN
4 6.0
5 8.0
dtype: float64
合并append
如果索引形同,则替换,无则添加
s1.append(s)
Out[117]:
a 测试
b 2
c 3
0 11111
1 3
2 5
3 NaN
4 6
5 8
dtype: object
s[0] ='改变了'
s
Out[121]:
0 改变了
1 3
2 5
3 NaN
4 6
5 8
dtype: object
s1.append(s)
Out[122]:
a 测试
b 2
c 3
0 改变了
1 3
2 5
3 NaN
4 6
5 8
dtype: object
DataFrame
DataFrame是一个表格型的数据结构,它含有一组有序的列,每列可以是不同的值类型(数值、字符串、布尔型值)。DataFrame既有行索引也有列索引,它可以被看做由Series组成的字典(共同用一个索引)。和其他类似的数据结构相比,DataFrame中面向行和面向列的操作基本上是平衡的。其实,DataFrame中的数据是以一个或多个二维块存放的(而不是列表、字典或别的数据结构)。
>>> data = {'state':['1','2'],'year':['a','b'],'pop':['x','y']}
>>> data
{'state': ['1', '2'], 'pop': ['x', 'y'], 'year': ['a', 'b']}
>>> frame = DataFrame(data)
>>> frame
pop state year
0 x 1 a
1 y 2 b
结果DataFrame会自动加上索引,且全部列会被有序排列。
如果指定了列顺序,则DataFrame的列就会按照指定顺序进行排列。>>> DataFrame(data,columns=['year','pop','state'])
year pop state
0 a x 1
1 b y 2
help(df.drop)
Help on method drop in module pandas.core.generic:
drop(labels=None, axis=0, index=None, columns=None, level=None, inplace=False, errors='raise') method of pandas.core.frame.DataFrame instance
Return new object with labels in requested axis removed.
Parameters
----------
labels : single label or list-like
Index or column labels to drop.
axis : int or axis name
Whether to drop labels from the index (0 / 'index') or
columns (1 / 'columns').
index, columns : single label or list-like
Alternative to specifying `axis` (``labels, axis=1`` is
equivalent to ``columns=labels``).
.. versionadded:: 0.21.0
level : int or level name, default None
For MultiIndex
inplace : bool, default False
If True, do operation inplace and return None.
errors : {'ignore', 'raise'}, default 'raise'
If 'ignore', suppress error and existing labels are dropped.
Returns
-------
dropped : type of caller
Examples
--------
df = pd.DataFrame(np.arange(12).reshape(3,4),
columns=['A', 'B', 'C', 'D'])
df
A B C D
0 0 1 2 3
1 4 5 6 7
2 8 9 10 11
Drop columns
df.drop(['B', 'C'], axis=1)
A D
0 0 3
1 4 7
2 8 11
###['B', 'C'])中。B和C中间有个空格
df.drop(columns=['B', 'C'])A D
0 0 3
1 4 7
2 8 11
Drop a row by index
df.drop([0, 1])
A B C D
2 8 9 10 11
Notes
-----
Specifying both `labels` and `index` or `columns` will raise a
ValueError.