问题
I want to operate in Octave in a similar manner as done with python pandas. I concluded the most similar object to a dataframe in Octave is a struct.
I have a few related questions.
- How can I create a new field 'nf' in struct
mystr
, by operating (row-by-row) on other fields inmystr
? Say, for fieldsa
,b
, I would like to getnf = a^b
. So far, I am using a loop, which I mean to avoid if possible.
ndata = size(mystr)(1);
for id = 1:ndata
mystr(id).nf = mystr(id).a ^ mystr(id).b;
endfor
How can I operate on shifted rows? Say, for fields
a
,b
, I would like to getnf[i] = a[i]^b[i-1]
(with proper accounting fori=1
). I guess I can work with a loop as above, but I mean to avoid it.How can I operate on fixed rows? Say, for fields
a
,b
, I would like to getnf[i] = a[i]^b[1]
. I guess I can work with a loop as above, but I mean to avoid it.
回答1:
Here is one way, using only comma separated lists and deal
.
S = struct( 'a', {1, 2}, 'b', {3, 4} ); % create a struct array
[ S.nf ] = deal( num2cell( [S.a] + [S.b] ){:} ); % deal to new field in array
However, I get the impression that you're after one-liners, rather than "efficiency" per se. Don't. This is ugly. There's nothing wrong with a for loop here.
Also, I fully agree with Cris's comment. It's best to rethink your approach. Doing something like the code below is presumably much more preferable than trying to perform operations over struct arrays:
S.a = [1,2];
S.b = [2,4];
S.nf = S.a + S.b;
I hasten to note that this is effectively what a dataframe is in R too: a bunch of same-sized vectors, each represented by their own fieldname, and packaged inside an object which allows you to access each array by its fieldname.
来源:https://stackoverflow.com/questions/62437993/pandas-like-object-in-octave-add-a-field-to-a-struct-by-operating-on-other-fiel