python将二维数组升为一维数组 或 二维降为一维

1. 二维(多维)数组降为一维数组

方法1: reshape()+concatenate 函数

  • 这个方法是间接法,利用 reshape() 函数的属性,间接的把二维数组转换为一维数组;
import numpy as np

mulArrays = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
print(list(np.concatenate(mulArrays.reshape((-1, 1), order="F"))))

Out[1]:
[1, 4, 7, 2, 5, 8, 3, 6, 9]

方法2: flatten() 函数

  • 推荐使用这个方法,这个方法是 numpy 自带的函数;
# coding = utf-8
import numpy as np
import random

# 把二维数组转换为一维数组
t1 = np.arange(12)
print(t1)
Out[0]: [ 0  1  2  3  4  5  6  7  8  9 10 11]
t2 = t1.reshape(3, 4)
print(t2)
 
t3 = t2.reshape(t2.shape[0] * t2.shape[1], )
print(t3)
 
t4 = t2.flatten()
print(t4)

运行效果如下图所示:
在这里插入图片描述
可以看到这两种方式都可以把二维数组转换为一维数组,但是推荐使用 flatten() 函数,该方法也可以将多维数组转换为一维数组。

import numpy as np
a = np.array([[1, 2], [3, 4], [9, 8]])
b = a.flatten()
print(b)

输出结果为:[1, 2, 3, 4, 9, 8]

方法3: itertools.chain

import numpy as np
a = np.array([[1, 2], [3, 4], [9, 8]])

# 使用库函数
from itertools import chain
a_a = list(chain.from_iterable(a))
print(a_a)

输出结果为:[1, 2, 3, 4, 9, 8]

方法4: sum()

mulArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(sum(mulArrays, []))  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

方法5:operator.add + reduce

import operator
from functools import reduce
mulArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print(reduce(operator.add, mulArrays))  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

方法6:列表推导式

mulArrays = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
print([i for arr in mulArrays for i in arr])  # [1, 2, 3, 4, 5, 6, 7, 8, 9]

2. 一维数组升为 2 维数组

方法1:numpy 方法

利用函数 reshape 或者是 resize

使用 reshape 的时候需要注意 reshape 的结果不改变,因此适用于还要用到原数组的情况。

使用 resize 会改变原数组,因此适用于一定需要修改后的结果为值的情况。

import numpy as np

x = np.arange(20)  # 生成数组
print(x)

result = x.reshape((4, 5))  # 将一维数组变成4行5列  原数组不会被修改或者覆盖
x.resize((2, 10))  # 覆盖原来的数据将新的结果给原来的数组
print(x)

输出结果

[ 0  1  2  3  4  5  6  7  8  9 10 11 12 13 14 15 16 17 18 19]

[[ 0  1  2  3  4  5  6  7  8  9]
 [10 11 12 13 14 15 16 17 18 19]]

3. 截取一列,转为list

import random
import pandas as pd

names = ['南宫婉', '雅菲', '余靖秋', '姜立', '小舞', '胡列娜', '比比东', '云韵', '美杜莎', '焰灵姬']
df = pd.DataFrame(
    {
        "age": [random.randint(18, 25) for i in range(len(names))],
        "height": [round(random.uniform(1.6, 1.75), 2) for i in range(len(names))],
        "weight": [random.randint(45, 50) for i in range(len(names))],
    }
)
>>> df
df
Out[29]: 
   age  height  weight
0   22    1.73      48
1   25    1.75      48
2   21    1.69      45
3   19    1.66      46
4   18    1.63      50
5   24    1.70      47
6   18    1.70      50
7   24    1.67      48
8   24    1.74      48
9   21    1.74      48
np.array(df.iloc[1:7, 1:2]).tolist()
Out[8]: [[1.75], [1.69], [1.66], [1.63], [1.7], [1.7]]

from tkinter import _flatten
list(_flatten(np.array(df.iloc[1:7, 1:2]).tolist()))
Out[26]: [1.75, 1.69, 1.66, 1.63, 1.7, 1.7]

np.array(df.iloc[1:7, 1:2]).flatten().tolist()
Out[28]: [1.75, 1.69, 1.66, 1.63, 1.7, 1.7]

文章出处登录后可见!

已经登录?立即刷新

共计人评分,平均

到目前为止还没有投票!成为第一位评论此文章。

(0)
扎眼的阳光的头像扎眼的阳光普通用户
上一篇 2023年3月5日 下午4:49
下一篇 2023年3月5日

相关推荐