python 将Excel中的(x,y)坐标列表返回为矩阵形式

x33g5p2x  于 2023-04-28  发布在  Python
关注(0)|答案(4)|浏览(174)

我有一个Excel文件,其中有2列表示X和Y坐标,我想将它们转换为矩阵格式,如:[X1,Y1]、[X2,Y2]、.……我怎么能这么做?非常感谢

我试过VBA Excel和Python,但我不知道如何做到这一点。

egmofgnx

egmofgnx1#

(1)您可以使用Excel公式来解决此任务:
D2:=“[”& A2 &“,“& B2 &“]”
复制到D列的最后一个单元格
E2:= D2
E3:= E2 &“,“& D3
复制到E列的最后一个单元格
(2)使用vba

Function create_matrix_format(myRange As Range) As String
Dim firstCell As Boolean
Dim nextLineStr As String
Dim resultStr As String
    firstCell = True
    For Each mycell In myRange
        If resultStr <> "" And firstCell Then resultStr = resultStr & ", "
        If firstCell Then
            nextLineStr = "[" & mycell.Value & ", "
            firstCell = False
        Else
            nextLineStr = nextLineStr & mycell.Value & "]"
            firstCell = True
            resultStr = resultStr & nextLineStr
        End If
    Next mycell
    create_matrix_format = resultStr
End Function

并在单元格中调用此函数:
例如D5:=create_matrix_format(A2:B4)

9lowa7mx

9lowa7mx2#

基于公式的替代方案:

=TEXTJOIN(", ",,"["&A2:A4&", "&B2:B4&"]")
roqulrg3

roqulrg33#

在Excel vba中,您可以使用UDF:

Function create_matrix(rng As Range) As String
    Dim rw As Range, element As Range
    output = "["
    For Each rw In rng.Rows
        For Each element In rw.Cells
            output = output & element.Value & ", "
        Next
        output = Left(output, Len(output) - 2) & "], ["
    Next
    create_matrix = Left(output, Len(output) - 3)
End Function

下面是它的实际运行情况:

0s0u357o

0s0u357o4#

你可以把它们读到一个dataframe中:

import pandas as pd
df = pd.read_excel(r"C:\.....your_file_path_..\file_name")

print(df)

    X   Y
0   56  268
1   65  236
2   236 597

然后可以使用zip()

print([list(x) for x in zip(df['X'], df['Y'])])
#[[56, 268], [65, 236], [236, 597]]

或者

print(*[list(x) for x in zip(df['X'], df['Y'])])
#[56, 268] [65, 236] [236, 597]

相关问题