Py库函数分为两种, 一种是知道作用但是不知道用法, 这种主要给出example; 另一种是不知道有什么作用, 这种给出explanation.
索引: pd.Series, pd.DataFrame
References
- Pandas-Toturial in Github, 来自知乎专栏键盘数据侠
- Pandas Cookbook
- Numpy 入门教程
- Scipy小记 - 皮皮blog(作者其它文章也很好)
导入
import pandas #使用需要加前缀, 如pandas.Series()
import pandas as pd #使用需要加前缀, 如pd.Series()
from scipy import * #可以直接使用csr_matrix((3,4), dtype=int8).todense()
查看变量类型
>>> a = 5
>>> type(a)
>>> isinstance(a, float) #a是否为float
False
>>> isinstance(a, (int, float)) #a是否为其中一个类型
True
os模块
os.getcwd() #当前运行python程序的目录
current_path = os.path.realpath(__file__) #被运行的.py文件的目录
os.path.split(os.getcwd()) #('C:\\Users\\User1', 'Desktop')
sys.path.append(currentPath + os.sep + '../') #添加上级目录
Pandas
Series
Series是一组类似于一维数组的对象, 由数据和索引组成;
Series构造 两种构造方法; 若不加index=
, 会自动生成[0, n-1]
的索引
>>> obj = Series([4, -2, 3], index=['b', 'a', 'c'])
>>> obj2 = Series({'b': 4, 'a': -2, 'c': 3}) #也可以通过字典创建
b 4
a -2
c 3 #索引和数据
>>> obj.index = [1, 2, 3] #可以通过赋值的方式更改索引
Series操作
>>> obj[['a', 'b']]
a -2
b 4
>>> obj[obj > 0]
>>> obj * 2 #每个元素都*2
>>> np.exp(obj)
>>> 'b' not in obj #可以把obj看成字典, 判断`b`是否在索引中
False
obj.name
: Series对象和索引都有个name属性
>>> obj.name = 'aName'
>>> obj.index.name = 'indexName'
obj.unique()
: 返回这个Series的去重复版本(顺序按照在原Series的出现顺序)
DataFrame
DataFrame(df)是一个二维表格, 既有行索引也有列索引
df构造/读取/输出
#用等长列表或者numpy数组组成的字典
>>> data = {'key1': ['a','a','b','b','a'],
'key2': ['one','two','one','two','one'],
'data1': np.random.randn(5),
'data2': np.random.randn(5)}
>>> df = DataFrame(data)
#也可以指定column和index
>>> df = DataFrame(data, columns=['key1', 'data1'])
------
>>> df = pd.read_csv("df.csv", names=['key1', 'key2']) #添加列名
>>> df = pd.read_csv("df.csv", index_col=0) #将csv文件第一列作为索引
>>> df.to_csv(path, columns=None, header=True, index=True)
#columns是要输出的列, header和index可以控制是否输出列名和索引
切片/删除 切片
>>> df = df[df['age'] > 1] #选择年龄大于1的行
>>> df = df[df['age'].isin([28, 28])] #选择特定行
------ #开始排除特定行
>>> age_list = list(df.age)
>>> age_list.remove(18)
>>> age_list.remove(28)
>>> age_list
[16, 19, 22, 40, ...]
>>> df[df.age.isin(age_list)]
------
>>> df = df.dropna(axis=0, how='any') #删除存在NaN的空行, how='all'则删除全为NaN的行
>>> df = df[df['age'] != df['age']] #利用NaN != Nan的特性
可视化
>>> df.describe() #描述数值型列的求和, 均值, 方差等
>>> df.hist() #对于数值型每一列画一张(值-出现次数)图
高阶特性
>>> data = {'key1': ['a','a','b','b','a'],
'key2': ['one','two','one','two','one'],
'data1': np.random.randn(5),
'data2': np.random.randn(5)}
data1 data2 key1 key2
0 -0.410673 0.519378 a one
1 -2.120793 0.199074 a two
2 0.642216 -0.143671 b one
3 0.975133 -0.592994 b two
4 -1.017495 -0.530459 a one
>>> g = df['data1'].groupby(df['key1']) #g为GroupBy类型变量
>>> g2 = df.groupby([df['key1'], df['key2']])
#将data1这一列按照key1不同的值来分组; 将df整个按照key1, key2分组
>>> g.size()
key1
a 3 #key1=a的组有3个
b 2 #key1=b的组有2个
>>> pd.crosstab(df.key1, df.key2, margins=True) #交叉2列来统计信息
key2 one two All
key1
a 2 1 3 #key2=one, key1=a的样本个数有2个
b 1 1 2
All 3 2 5
>>>
df.sort_values(by, axis=0, ascending=True)
: 按照某一列递增排序, by
后面加列的名字
df['aColumn'].apply(func)
: 对某一列应用一个函数, 比如lambda
函数:lambda x: x * 2
(格式是lambda input: output
)
pd.get_dummies()
: 对DataFrame进行one-hot编码, 此函数在输入的DataFrame基础上, 把指定的columns
里面的列变成dummy后的列
>>> df = pd.DataFrame({'gender': ['m', 'f', 'f'],
'school': ['sjtu', 'fdu', 'fdu']})
gender school
0 m sjtu
1 f fdu
2 f fdu
>>> pd.get_dummies(df['gender'], prefix='g') #单列进行one-hot编码
g_f g_m
0 0 1
1 1 0
2 1 0
>>> pd.get_dummies(df, columns=['school'], sparse=True)
#用columns指定哪些列(必须, 否则可能编码不出来), 并用稀疏矩阵存储
gender school_fdu school_sjtu
0 m 0 1
1 f 1 0
2 f 1 0
NumPy
numpy最重要的是N维数组对象ndarray
, 其有ndim
(维数/秩, rank), shape
(形状)和dtype
(元素类型)三个重要属性(无特别指定, 数据类型都是双精度浮点值float64)
构造ndarray
>>> a = [[1, 2, 3], [4, 5.1, 6]]
>>> arr = np.array(a) #用数组构造
array([[ 1. , 2. , 3. ],
[ 4. , 5.1, 6. ]])
#arr.ndim: 2, arr.shape: (2, 3), arr.dtype: dtype('float64')
>>> arr2 = np.arange(10, 25, 5) #和range()函数类似, 注意左开右闭
array([10, 15, 20])
>>> arr3 = np.arange(6).reshape((2, -1)) #构造多为数组, reshape参数的一个分量可以为-1
array([[0, 1, 2],
[3, 4, 5]])
>>> np.zeros(3) #构造全0数组
array([ 0., 0., 0.])
>>> np.ones((2, 2)) #构造全1数组
array([[ 1., 1.],
[ 1., 1.]])
数组运算 数学运算都是针对每个元素进行计算的
>>> arr2 = arr1 + arr1
>>> arr2 = arr1 * arr1 #每个元素相乘, 不是矩阵相乘
>>> arr1 * 2 #每个元素*2, 不会修改原数组!
>>> arr1 ** 3 #每个元素的3次幂
>>> 1 / arr1 #每个元素取倒数
高阶特性
np.random.shuffle(a)
: 将第0维元素的顺序随机改变一下, 输入可以是一维的list也可以是多维的arrary_like; 该函数无返回值, 直接在输入上进行修改.
cs231n Assignment
[1, 2, 3]
是行向量, [[1], [2], [3]]
才是列向量. [1, 2, 3]
和[[1, 2, 3]]
有什么区别?
N, D = X.shape
: 把秩为2的X的维度赋给N和D.
a[range(2), 1]
: 依次取坐标位于(0,1), (1,1)的元素, 注意到range()是个迭代器.
np.argmax(a, axis=None)
: 返回a中最大值在的位置, 如果axis=None, 则返回在一维化(flattened)的a中的位置; 若axis=0, 则返回在每一列的位置.
np.maximum(a, b)
: a和b两个ndarray每一位对比, 选最大的; 注意这里可以有broadcast广播机制, 比如a
为整数0也是合法的.
np.amax(a, axis=None, keepdims=True)
: 若不输入axis, 取a中最大的元素; 若axis=0, 则按照纵向选取每列的最大值, 组成一个行向量, 此时加上keepdims=True, 则输出另一种行向量, 即类似于[[1, 2, 3]]
; 若axis=1, 则按照横向选取每行的最大值, 也组成一个行向量, 此时加上keepdims=True, 则输出列向量, 即类似于[[1], [2], [3]]
.
np.sum(a, axis=None, keepdims=True)
: 类似于np.amax()
.
np.random.rand(a, b)
: 返回一个a*b的float类型的ndarray, 每个元素服从N(0,1)分布.
np.random.choice(a, size, replace=True)
: a可以是int或者list, 从a中一采样size次, 返回一个size大小的array. 其中int类型的a会自动转为np.arange(a), True表示有重复的采样(速度更快).
np.vstack([a, b])
: 纵向合并两个ndarray, 等价于np.concatenate([a, b], axis=1)
; 对应的还有np.hstack()
; 注意, 不要使用np.stack()
, 太复杂.
SciPy
稀疏矩阵
bsr_matrix(arg1[, shape, dtype, copy, blocksize]) #Block Sparse Row matrix
coo_matrix(arg1[, shape, dtype, copy]) #A sparse matrix in COOrdinate format.
csc_matrix(arg1[, shape, dtype, copy]) #Compressed Sparse Column matrix
csr_matrix(arg1[, shape, dtype, copy]) #Compressed Sparse Row matrix
dia_matrix(arg1[, shape, dtype, copy]) #Sparse matrix with DIAgonal storage
dok_matrix(arg1[, shape, dtype, copy]) #Dictionary Of Keys based sparse matrix.
lil_matrix(arg1[, shape, dtype, copy]) #Row-based linked list sparse matrix
Compressed Sparse Column matrix (CSC)
>>> indptr = np.array([0, 2, 3, 6]) #index pointer
>>> indices = np.array([0, 2, 2, 0, 1, 2])
>>> data = np.array([1, 2, 3, 4, 5, 6])
>>> csc_matrix((data, indices, indptr), shape=(3, 3)).toarray()
array([[1, 0, 4],
[0, 0, 5],
[2, 3, 6]])
indptr
表示的是indices
矩阵里的开始和结尾的index, indptr[0, 2]
表示indices[0:2]
存储了第一列的数据所位置0行和2行, indices[2:3]
存储了第二列的数据位置, 即2, 第2行(注意从0行开始), 每个indices[i]
对应一个data[i]
. 实际上indeces[0:2]
只取了indices
第一个和第二个数值0和2,代表数据在0和2行,其余位置皆为0; inices[2:3]
取了indices[2]
的数值2,代表数据在第2行,其余位置皆为0.
sparse matrix in COOrdinate format (COO)
>>> row = np.array([0, 3, 1, 0])
>>> col = np.array([0, 3, 1, 2])
>>> data = np.array([4, 5, 7, 9])
>>> coo_matrix((data, (row, col)), shape=(4, 4)).toarray()
array([[4, 0, 9, 0],
[0, 7, 0, 0],
[0, 0, 0, 0],
[0, 0, 0, 5]])
#矩阵第(row[i], col[i])个元素为data[i], 其余为0
Last updated on Jan 11, 2019.