Python 将 x、y 和 z 的列表转换为 matrix/table

Python transform list of x,y and z to matrix/table

我有格式列表:

[[x_0, y_0, z_0], [x_1, y_1, z_1] ... [x_n, y_n, z_n]]

哪里可以 x_0 == x_1:

[[0, 0, z_0], [0, 1, z_1], [0, 2, z_2]... [1, 0, z_o] ... [x_n, y_n, z_n]]

我想将它转换为这样的矩阵(创建 csv 文件会很好):

主要问题 - 我不知道数组的总大小(每次都会更改,但总是方形的)。 进行此类转换的最简单方法是什么?

列表是点的 XYZ 坐标。

使用pandas创建一个枢轴table。数据透视表 table 允许您以行格式获取数据并将其重新排列为行、列和值。

import pandas as pd
import random

# create some fake data

data = [(i,j,0.1*random.randrange(1,50,1)) for i in range(5) for j in range(5)]

# [(0, 0, 4.2), (0, 1, 1.9), (0, 2, 1.2), (0, 3, 1.2), (0, 4, 1.6),
#  (1, 0, 2.0), (1, 1, 0.9), (1, 2, 3.5), (1, 3, 3.0), (1, 4, 0.8),
#  (2, 0, 4.9), (2, 1, 2.8), (2, 2, 1.8), (2, 3, 2.7), (2, 4, 0.2),
#  (3, 0, 3.0), (3, 1, 1.8), (3, 2, 0.3,  (3, 3, 3.3), (3, 4, 4.4),
#  (4, 0, 1.9), (4, 1, 4.5), (4, 2, 3.6), (4, 3, 0.4), (4, 4, 0.4)]

# read it into a dataframe:
df = pd.DataFrame(data, columns=['x','y','z'])

# create pivot table with x and rows, y and columns, z as values
df.pivot_table(values='z', index='x', columns='y')

# y    0    1    2    3    4
# x
# 0  4.2  1.9  1.2  1.2  1.6
# 1  2.0  0.9  3.5  3.0  0.8
# 2  4.9  2.8  1.8  2.7  0.2
# 3  3.0  1.8  0.3  3.3  4.4
# 4  1.9  4.5  3.6  0.4  0.4

使用pandas和numpy

import pandas as pd
import numpy as np
import math

lis = [[0,0,3.4],[0,1,5.6],[1,0,4.3],[1,1,3.4]]

n2 = len(lis)
n = int(math.sqrt(n2))

nparray = np.zeros([n,n])

for l in lis:
    nparray[[l[0],l[1]]]=l[2]

print nparray
#[[ 4.3  4.3]
# [ 3.4  3.4]]

#Output to csv
df = pd.DataFrame(nparray)
df.to_csv('/some/path')

如果您想坚持使用标准库,这是一种方法。从数据中创建一个字典,然后使用字典键作为一种方法将内容排序为 CSV 格式;最后写入 CSV 文件:

# Data = your data formatted as described
resultsdict = {}
csvfile = ""
counter = 0

# create tuple-paired key dictionary of values (i.e. (0,0): 1.2, etc)
for pairs in data:
    if pairs[0] > counter:
        # track the square size
        counter = pairs[0]
    currentpairkey = (pairs[0], pairs[1])
    resultsdict[currentpairkey] = pairs[2]

# create raw CSV data
count = range(counter + 1)
for x in count:
    row = []
    for y in count:
        currentpairkey = (x, y)
        # this line is where you control your desired formatting.
        row.append("%s" % (resultsdict[currentpairkey]))
    print(row)
    csvfile += "%s\n" % ",".join(row)

# write CSV file
with open("results.csv", "w") as f:
    f.write(csvfile)