Octave中类似于 pandas 的对象:通过对其他字段进行操作将字段添加到结构中 [英] pandas-like object in Octave: add a field to a struct by operating on other fields

查看:65
本文介绍了Octave中类似于 pandas 的对象:通过对其他字段进行操作将字段添加到结构中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想以与Python熊猫类似的方式在Octave中进行操作. 我得出结论,与Octave中数据框最相似的对象是一个结构.

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.

我有几个相关问题.

  1. 如何通过对mystr中的其他字段进行操作(逐行)来在结构mystr中创建新的字段'nf'? 说,对于字段ab,我想获取nf = a^b. 到目前为止,我正在使用一个循环,如果可能的话,我想避免该循环.
  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. 如何处理移位的行? 说,对于字段ab,我想获取nf[i] = a[i]^b[i-1](对i=1进行适当说明). 我想我可以使用上面的循环,但是我要避免这种情况.

  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.

如何对固定行进行操作? 说,对于字段ab,我想获取nf[i] = a[i]^b[1]. 我想我可以使用上面的循环,但是我要避免这种情况.

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.

推荐答案

这里是一种方法,仅使用逗号分隔的列表和deal.

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

但是,我得到的印象是,您本来就一心一意,而不是效率"本身.别.这很丑.这里的for循环没有任何问题.

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.

我也完全同意Cris的评论.最好重新考虑您的方法.大概执行下面的代码比尝试对结构数组执行操作更可取:

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;

我不得不注意到,这实际上也是R中的数据帧:一堆相同大小的向量,每个向量都由它们自己的字段名表示,并包装在一个对象中,该对象使您可以按字段名访问每个数组.

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.

这篇关于Octave中类似于 pandas 的对象:通过对其他字段进行操作将字段添加到结构中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆