也许我可以用标题准确地综合我的问题,但是我想通过解释它,事情会变得更加清楚.
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数组的元素的不同组合组合到数据框中
发布评论