# 个人博客转至：tybai.com

## numpy操作

python中使用了numpy的一些操作，特此记录下来：

# 生成矩阵，替换值

import numpy as np
# 生成一行10列的矩阵
dataset = np.zeros((1, 10))
# 将位置为2的值替换为1
dataset.itemset(2, 1)

[[0. 0. 1. 0. 0. 0. 0. 0. 0. 0.]]

# where查找

import numpy as np
dataset = np.array([1, 2, 3, 2, 3, 4, 4, 5, 6])
# 找到值等于2的值的下标
dataset = np.where(dataset == 2)
print(dataset)

dataset = np.array([1, 2, 3, 2, 3, 4, 4, 5, 6])
index = np.argwhere(dataset == 2)
print(index)

(array([1, 3], dtype=int64),)

[[1]
[3]]

# 增加一行或一列

import numpy as np
dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
# 增加行
a = np.row_stack((dataset, [8,9,10]))
print(a)

# 增加列
b = np.column_stack((dataset, [8,9,10]))
print(b)

[[ 1  2  3]
[ 2  3  4]
[ 4  5  6]
[ 8  9 10]]

[[ 1  2  3  8]
[ 2  3  4  9]
[ 4  5  6 10]]

# 按行合并，按列合并

import numpy as np
dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
# 按行合并
dataset = np.append(dataset, [[8, 9, 10]], axis=0)
print(dataset)

dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
# 按列合并
dataset = np.append(dataset, [[8], [9], [10]], axis=1)
print(dataset)

[[ 1  2  3]
[ 2  3  4]
[ 4  5  6]
[ 8  9 10]]

[[ 1  2  3  8]
[ 2  3  4  9]
[ 4  5  6 10]]

# 删除行、列

import numpy as np
dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
# 删除第1、2行（0、1、2）
dataset = np.delete(dataset, [1, 2], axis=0)
print(dataset)

dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
# 删除第1、2列（0、1、2）
dataset = np.delete(dataset, [1, 2], axis=1)
print(dataset)

[[1 2 3]]

[[1]
[2]
[4]]

# ndarray转dataframe

import numpy as np
import pandas as pd

dataset = np.array([[1, 2, 3], [2, 3, 4], [4, 5, 6]])
dataframe = pd.DataFrame(dataset, index=("row1", "row2", "row3"), columns=("col1", "col2", "col3"))
print(dataframe)

      col1  col2  col3
row1     1     2     3
row2     2     3     4
row3     4     5     6

posted on 2018-09-28 11:09  TTyb  阅读(...)  评论(...编辑  收藏