Matlab struct array to python

前端 未结 1 534
野的像风
野的像风 2020-12-17 04:44

I have thoroughly looked around to try figuring out a way to create a matlab like struct array in python. There are some questions online that I looked at and either the ans

相关标签:
1条回答
  • 2020-12-17 05:39

    Update: You may want to investigate Pandas. Its Series and DataFrames are easier to work with and more full-featured than NumPy structured arrays.


    You could use a NumPy structured array:

    import numpy as np
    channel = np.zeros(1, dtype = [('PRN',int),
                                   ('acquiredFreq',int),
                                   ('codePhase',int),
                                   ('status','|S1')])
    
    print(channel)
    # [(0, 0, 0, '')]
    

    Indexing by integer accesses a particular row:

    print(channel[0])
    # (0, 0, 0, '')
    

    Indexing by column name returns the column as an array:

    print(channel['PRN'])
    # [0]
    

    Or you can loop through each row and assign to each field (column), but this is relatively slow in NumPy.

    for row in channel:
        row['PRN'] = 1
        row['acquiredFreq'] = 1
        row['codePhase'] = 1
        row['status'] = '+'
    
    print(channel)    
    # [(1, 1, 1, '+')]
    

    Just for completeness, I'll also mention you can assign by row then column:

    channel[0]['status'] = '-'
    print(channel)
    # [(1, 1, 1, '-')]
    

    or assign by column then row:

    channel['PRN'][0] = 10
    print(channel)
    # [(10, 1, 1, '-')]
    

    I showed the above because it is most similar to the Matlab code you posted. However, let me stress again that assigning to individual cells in a NumPy array is slow. The NumPy-way to do the above is to do whole-array assignments instead:

    channel['PRN'] = PRNindexes
    

    where PRNindexes is a sequence (e.g. a list, tuple, or NumPy array).


    You can also use fancy indexing (aka "advanced indexing") to select rows:

    index = (channel.status == '+')  # Select all rows with status '+'
    channel['PRN'][index] = 10       # Set PRN to 10 for all those rows
    

    Just keep in mind that fancy indexing returns a new array, not a view of the original array. (In contrast, "basic slicing" (e.g. channel[0] or channel[1:10] returns a view.) So if you want to make assignments that alter the original array, select by column first, then fancy index (index)

    channel['PRN'][index] = ...
    

    rather than

    channel[index]['PRN'] = ...
    
    0 讨论(0)
提交回复
热议问题