将numpy数组的元素的不同组合组合到数据框中

编程入门 行业动态 更新时间:2024-10-10 18:19:55
本文介绍了将numpy数组的元素的不同组合组合到数据框中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

也许我可以用标题准确地综合我的问题,但是我想通过解释它,事情会变得更加清楚.

Maybe I could synthesize precisely my problem with my title, however I guess that by explaning it, things will get more clear.

因此,我要执行以下操作:我想创建一个数据框,每一行将4个不同的numpy数组的每个不同元素组合在一起.

So, what I want to do is the following: I want to create a dataframe which each row combinates each distinct element of 4 different numpy arrays.

我正在尝试尽可能避免for循环,并且我不确定是否还有其他方法可以利用我尚不了解的pandas或python方法来实现我的目标.我要解决的问题自然会更加复杂,并且会涉及更多的数组以及更复杂的数据.

I am trying to avoid for loops as much as possible and I am not sure if there are other means to achieve my goal utilizing pandas or python methods which I am not still aware of. The problem that I am trying to solve is naturally more complex and would involve several more arrays as well as more complex data.

非常感谢您在此方面的帮助!

I would really appreciate your help on this one!

min_x = 1 max_x = 5 x1_set = np.linspace(min_x, max_x, 5) x2_set = np.linspace(min_x, max_x, 5) x3_set = np.linspace(min_x, max_x, 5) x4_set = np.linspace(min_x, max_x, 5) X_set_df = pd.DataFrame([x1_set,x2_set,x3_set,x4_set]).T

我希望这样的数据框

I would expect a dataframe that would be somehow like this

First row : 1,1,1,1 Second row: 1,1,1,2 Third row: 1,1,1,3 ... n-row: 5,5,5,5

推荐答案

使用 itertools.product 用于笛卡尔积,最后将其传递给 DataFrame 构造函数:

from itertools import product df = pd.DataFrame(list(product(*[x1_set,x2_set,x3_set,x4_set]))) print (df) 0 1 2 3 0 1.0 1.0 1.0 1.0 1 1.0 1.0 1.0 2.0 2 1.0 1.0 1.0 3.0 3 1.0 1.0 1.0 4.0 4 1.0 1.0 1.0 5.0 .. ... ... ... ... 620 5.0 5.0 5.0 1.0 621 5.0 5.0 5.0 2.0 622 5.0 5.0 5.0 3.0 623 5.0 5.0 5.0 4.0 624 5.0 5.0 5.0 5.0 [625 rows x 4 columns]

更多推荐

将numpy数组的元素的不同组合组合到数据框中

本文发布于:2023-11-29 13:34:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1646529.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:组合   数组   框中   元素   数据

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!