常用Py包和函数汇总

Numpy

  • 学习来源:
    https://morvanzhou.github.io/tutorials/data-manipulation/np-pd/2-2-np-array/
  • numpy 的属性:
    • ndim:维度
    • shape:行数和列数
    • size:元素个数
  • 创建 array:
    • array:创建数组
    • dtype:指定数据类型
    • zeros:创建数据全为0
    • ones:创建数据全为1
    • empty:创建数据接近0
    • arrange:按指定范围创建数据
    • linspace:创建线段
  • 基础运算
    • 矩阵乘法:
      • 对应元素相乘:a*b
      • 矩阵乘法:np.dot(a,b) 或 a.dot(b)
    • 矩阵聚合操作:如果你需要对行或者列进行查找运算,就需要在上述代码中为 axis 进行赋值。
      • 当axis的值为0的时候,将会以列作为查找单元。
      • 当axis的值为1的时候,将会以行作为查找单元。
    • 描述统计:
      • a.mean() / a.average() / a.median()
    • np.nonzero(A),将所有非零元素的行与列坐标分割开,重构成两个分别关于行和列的矩阵。
    • 矩阵转置:
      • print(np.transpose(A))
      • print(A.T)
  • 索引
    • 一维索引:A[3]
      • 一维(数组形式),表示第4个元素
      • 二维(矩阵形式),表示第四行的所有元素(是个list)
    • 二维索引:
      • A[1][1] / A[1,1] 表示第二行第二列的元素
      • A[1, 1:3] 支持切片
    • 迭代输出
import numpy as np
A = np.arange(3,15).reshape((3,4))

print(A.flatten())   
# array([3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14])

for item in A.flat:
    print(item)

# 3
# 4
……
# 14
  • array合并
    • 上下合并 vertical stack : np.vstack((A,B)) 两个括号
    • 左右合并 horizontal stack:np.hstack((A,B))
    • 和并多个矩阵:np.concatenate()
  • array分割
    • 横向:np.split(A, 2, axis=0)
    • 纵向:np.split(A, 2, axis=1)
    • 不等量分割:np.array_split(A, 3, axis=1),若有4列,前两列会成为一个array,5列是(2,2,1)
  • array copy/deep copy
    • b=a.copy(),改变a,b不变

Pandas

  • 学习来源:
    https://morvanzhou.github.io/tutorials/data-manipulation/np-pd/2-2-np-array/
  • 如果用 python 的列表和字典来作比较, 那么可以说 Numpy 是列表形式的,没有数值标签,而 Pandas 就是字典形式。Pandas是基于Numpy构建的,让Numpy为中心的应用变得更加简单。
  • pd.Series:Series的字符串表现形式为:索引在左边,值在右边。由于我们没有为数据指定索引。于是会自动创建一个0到N-1(N为长度)的整数型索引。
  • pd.DataFrame:DataFrame是一个表格型的数据结构,它包含有一组有序的列,每列可以是不同的值类型(数值,字符串,布尔值等)。DataFrame既有行索引也有列索引, 它可以被看做由Series组成的大字典。
    • pd.DataFrame(np.random.randn(6,4),index=dates,columns=[‘a’,’b’,’c’,’d’])
    • 类比 R 的数据框data.frame
  • 选择数据
    • 索引columns:df[‘A’]
      • 多列:df[[‘A’,’B’]]
      • 转换为array:df[‘A’].values
    • 索引index:df[0:3]
    • 索引标签loc:df.loc[:,[‘A’,’B’]](取A、B列)
    • 索引序列iloc:df.iloc[3:5,1:3] (第4、5行,第2、3列,不包括第6行(5)、第4列(3))
      • 双冒号作用, 序列切片地址可以写为[开始:结束:步长]
    • 索引标签/序列ix:df.ix[:3,[‘A’,’C’]](选择’A’和’C’的两列,并选择前三行的数据。)
    • 判断筛选:
      • df[df.A>8]
      • df[df.index==’2013-01-04’])
  • 设置值

    • 根据位置设置
      • df.iloc[2,2] = 1111
      • df.loc[‘20130101’,’B’] = 2222
    • 根据条件设置
      • 如果现在的判断条件是这样, 我们想要更改B中的数, 而更改的位置是取决于 A 的. 对于A大于4的位置. 更改B在相应位置上的数为0.
      • df.B[df.A>4] = 0
    • 添加数据:Series序列
      • df[‘E’] = pd.Series([1,2,3,4,5,6], index=pd.date_range(‘20130101’,periods=6))
  • 处理丢失数据:有时候我们导入或处理数据, 会产生一些空的或者是 NaN 数据,如何删除或者是填补这些 NaN 数据.

    • pd.dropna(),如果想直接去掉有 NaN 的行或列。
    • pd.fillna():如果是将 NaN 的值用其他值代替, 比如代替成 0。df.fillna(value=0)
    • pd.isnull():判断是否有缺失数据 NaN, 为 True 表示缺失数据。
    • np.any(df.isnull()) == True:检测在数据中是否存在 NaN, 如果存在就返回 True
df.dropna(
    axis=0,     # 0: 对行进行操作; 1: 对列进行操作
    how='any'   # 'any': 只要存在 NaN 就 drop 掉; 'all': 必须全部是 NaN 才 drop 
    ) 
  • Pandas导入导出

  • Pandas合并concat

    • axis(上下),重置index:
      • pd.concat([df1, df2, df3], axis=0, ignore_index=True)
    • join(左右),此方式是依照column合并,默认outer。
      • pd.concat([df1, df2], axis=0, join=’inner’, ignore_index=True)
    • join_axes(依照axes合并),此方式是依照index合并,默认’outer’。
#定义资料集
df1 = pd.DataFrame(np.ones((3,4))*0, columns=['a','b','c','d'], index=[1,2,3])
df2 = pd.DataFrame(np.ones((3,4))*1, columns=['b','c','d','e'], index=[2,3,4])

#依照`df1.index`进行横向合并
res = pd.concat([df1, df2], axis=1, join_axes=[df1.index])

#打印结果
print(res)
#     a    b    c    d    b    c    d    e
# 1  0.0  0.0  0.0  0.0  NaN  NaN  NaN  NaN
# 2  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0
# 3  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0

#移除join_axes,并打印结果
res = pd.concat([df1, df2], axis=1)
print(res)
#     a    b    c    d    b    c    d    e
# 1  0.0  0.0  0.0  0.0  NaN  NaN  NaN  NaN
# 2  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0
# 3  0.0  0.0  0.0  0.0  1.0  1.0  1.0  1.0
# 4  NaN  NaN  NaN  NaN  1.0  1.0  1.0  1.0
  • append添加数据,只有纵向合并
    • 合并多个,需要先逐个合并(递归函数)
    • res = df1.append([df2, df3], ignore_index=True)
  • 合并merge(sql语法)

    • 主要用于两组有key column的数据,统一索引的数据. 通常也被用在Database的处理当中.
    • 依据一组key合并:pd.merge(left, right, on=’key’, how=’inner’) 等价于left join right on l.key=r.key
    • 依据两组key合并: pd.merge(left, right, on=[‘key1’, ‘key2’], how=’outer’)
    • indicator=true,将合并的记录放在心得一列。pd.merge(df1, df2, on=’col1’, how=’outer’, indicator=True)
    • 依据index合并
      • pd.merge(left, right, left_index=True, right_index=True, how=’inner’)
    • 解决overlapping问题:a按index找相同
      • pd.merge(boys, girls, on=’k’, suffixes=[‘_boy’, ‘_girl’], how=’inner’)
  • Pandas plot出图

  • matplotlib
    • print dataframe
    • print series
    • scatter
      • data.plot.scatter(x=’A’,y=’C’,color=’LightGreen’,label=’Class2’,ax=ax)
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值