pandas-like object in Octave: add a field to a struct by operating on other fields [closed]

你离开我真会死。 提交于 2020-06-23 12:18:38

问题


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.

  1. How can I create a new field 'nf' in struct mystr, by operating (row-by-row) on other fields in mystr? Say, for fields a, b, I would like to get nf = 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
  1. How can I operate on shifted rows? Say, for fields a, b, I would like to get nf[i] = a[i]^b[i-1] (with proper accounting for i=1). I guess I can work with a loop as above, but I mean to avoid it.

  2. How can I operate on fixed rows? Say, for fields a, b, I would like to get nf[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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!