gpt4 book ai didi

python - 将 Numpy 数组拆分为每列的数组

转载 作者:太空宇宙 更新时间:2023-11-04 02:18:30 24 4
gpt4 key购买 nike

我有一个 Numpy 数组作为列表的列表,维度为 n x 4(行,列)。我试图将来自每个单独列表实例的数据分成四个单独的数组,每个数组包含来自单个列的所有信息,因此我可以将它添加到 pandas 数据框中。从此:

[[126 188 166   1]
[111 173 149 1]
[ 81 119 123 2]
[ 83 122 124 2]
[ 84 122 124 2]
[255 255 255 3]
[255 255 255 3]
[255 255 255 3]]

对此:

bBand = [126,111,81,...,255]
gBand = [188,173,119,...,255]
rBand = [166,149,123,...,255]
class = [1,1,2,...,3]

当前代码:

   MasterList = np.arrray([[126, 188, 166,   1],[111, 173, 149,   1],[ 81, 119, 123,   2],[ 83, 122, 124,   2],[ 84, 122, 124,   2],[255, 255, 255,   3],[255, 255, 255,   3],[255, 255, 255,   3]])
print(MasterList)
columns = ["bBand","gBand","rBand","class"]
df = pd.DataFrame(MasterList.reshape(-1, len(MasterList)),columns=columns)

最佳答案

正如@DSM 提到的,您可以这样做:

import numpy as np
import pandas as pd

data = np.array([[126, 188, 166, 1],
[111, 173, 149, 1],
[81, 119, 123, 2],
[83, 122, 124, 2],
[84, 122, 124, 2],
[255, 255, 255, 3],
[255, 255, 255, 3],
[255, 255, 255, 3]])

frame = pd.DataFrame(data=data, columns=["bBand","gBand","rBand","class"])
print(frame)

输出

   bBand  gBand  rBand  class
0 126 188 166 1
1 111 173 149 1
2 81 119 123 2
3 83 122 124 2
4 84 122 124 2
5 255 255 255 3
6 255 255 255 3
7 255 255 255 3

不需要 reshape 数组。如果你想要单独的列表,你可以试试这个:

data = np.array([[126, 188, 166, 1],
[111, 173, 149, 1],
[81, 119, 123, 2],
[83, 122, 124, 2],
[84, 122, 124, 2],
[255, 255, 255, 3],
[255, 255, 255, 3],
[255, 255, 255, 3]])


for name, column in zip(["bBand","gBand","rBand","class"], data.T):
print(name, column)

输出

bBand [126 111  81  83  84 255 255 255]
gBand [188 173 119 122 122 255 255 255]
rBand [166 149 123 124 124 255 255 255]
class [1 1 2 2 2 3 3 3]

最后你可以直接设置值了:

bBand = list(data[:, 0])
gBand = list(data[:, 1])
rBand = list(data[:, 2])
_class = list(data[:, 3])

关于python - 将 Numpy 数组拆分为每列的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52101988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com