gpt4 book ai didi

python - python 中的矩阵 : transposing 2nd column into matrix row then populating with data in 3rd column

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:16 25 4
gpt4 key购买 nike

这里是 python 新手(但有 R、SQL 经验)。我尝试用谷歌搜索这个,但无法产生新的想法。我的主要目的是使用 csv 数据生成矩阵,但我想将第二列转置为矩阵的行。然后,我想用第三列中的数据填充该矩阵,但无法到达任何地方。

几天后,我想出了这段代码:

    import csv
def readcsv(csvfile_name):
with open(csvfile_name) as csvfile:
file=csv.reader(csvfile, delimiter=",")
#remove rubbish data in first few rows
skiprows = int(input('Number of rows to skip? '))
for i in range(skiprows):
_ = next(file)

#change strings into integers/floats
for z in file:
z[:2]=map(int, z[:2])
z[2:]=map(float, z[2:])
print(z[:2])
return

这只是清理我的数据,但是我想做的是将数据转置为矩阵。我拥有的数据是这样的(想象x,y,z,d和其他字母是 float ):

       1  1  x
1 2 y
1 3 z
1 4 d
. . .
. . .

但是,我想将这些数据转换成这样的矩阵:即我想用第三列中的数据填充该矩阵(这里的字母只是为了让你们更容易阅读)并转换将第二列转换为矩阵的一行。因此本质上,该 CSV 文件的第一列和第二列是矩阵的坐标。

          1  2  3  4  .  .
1 x y z d
1 a b c u
1 e f e y
.
.

我尝试学习 numpy,但是它似乎要求我的数据已经是矩阵形式。

最佳答案

如果您想使用 numpy,您有两个选项,具体取决于数据的存储方式。

  1. 如果保证您的 key 持续增加,例如:

     THIS    NOT THIS
    ------ --------
    1 1 a 1 1 a
    1 2 b 1 3 b
    1 3 c 2 1 c
    1 4 d 3 1 d
    2 1 e 1 2 e
    2 2 f 1 4 f
    2 3 g 8 8 g
    2 4 h 2 2 h

    然后只需将最右列中的所有值放入一个平面 numpy 数组中,并根据左列和中列中的最大值重新整形即可。

    import numpy as np
    m = np.array(right_column)
    # For the sake of example:
    #: array([1., 2., 3., 4., 5., 6., 7., 8.])
    m = m.reshape(max(left_column), max(middle_column))
    #: array([[1., 2., 3., 4.],
    #: [5., 6., 7., 8.]])
  2. 如果不能保证,您可以对其进行排序(可能是最简单的),或者创建一个正确形状的零数组并循环遍历每个元素。

    # Example data
    left_column = [1, 2, 1, 2, 1, 2, 1, 2]
    middle_column = [1, 1, 3, 3, 2, 2, 4, 4]
    right_column = [1., 5., 3., 7., 2., 6., 4., 8.]

    import numpy as np
    m = np.zeros((max(left_column), max(middle_column)), dtype=np.float)
    for x, y, z in zip(left_column, middle_column, right_column):
    x -= 1 # Because the indicies are 1-based
    y -= 1 # Need to be 0-based
    m[x, y] = z

    print(m)
    #: array([[ 1., 2., 3., 4.],
    #: [ 5., 6., 7., 8.]])

关于python - python 中的矩阵 : transposing 2nd column into matrix row then populating with data in 3rd column,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40229875/

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