如何在python中将3d数组转换为数据框 [英] How to transform a 3d arrays into a dataframe in python

查看:47
本文介绍了如何在python中将3d数组转换为数据框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个3d数组,如下所示:

I have a 3d arrays as follows:

ThreeD_Arrays = np.random.randint(0, 1000, (5, 4, 3))

array([[[715, 226, 632],
        [305,  97, 534],
        [ 88, 592, 902],
        [172, 932, 263]],

       [[895, 837, 431],
        [649, 717,  39],
        [363, 121, 274],
        [334, 359, 816]],

       [[520, 692, 230],
        [452, 816, 887],
        [688, 509, 770],
        [290, 856, 584]],

       [[286, 358, 462],
        [831,  26, 332],
        [424, 178, 642],
        [955,  42, 938]], 

       [[ 44, 119, 757],
        [908, 937, 728],
        [809,  28, 442],
        [832, 220, 348]]])

现在我想将其放入这样的数据帧中:

Now I would like to have it into a DATAFRAME like this:

添加如所示的 Date 列和列名 A B C

Add a Date column like indicated and the column name A, B, C.

如何进行此转换?谢谢!

How to do this transformation? Thanks!

推荐答案

基于对这个问题,我们可以使用MultiIndex。首先,创建MultiIndex和一个展平的DataFrame。

Based on the answer to this question, we can use a MultiIndex. First, create the MultiIndex and a flattened DataFrame.

A = np.random.randint(0, 1000, (5, 4, 3))

names = ['x', 'y', 'z']
index = pd.MultiIndex.from_product([range(s)for s in A.shape], names=names)
df = pd.DataFrame({'A': A.flatten()}, index=index)['A']

现在我们可以重塑它,但是我们喜欢:

Now we can reshape it however we like:

df = df.unstack(level='x').swaplevel().sort_index()
df.columns = ['A', 'B', 'C']
df.index.names = ['DATE', 'i']

这是结果:

          A    B    C
DATE i           
0    0  715  226  632
     1  895  837  431
     2  520  692  230
     3  286  358  462
     4   44  119  757
1    0  305   97  534
     1  649  717   39
     2  452  816  887
     3  831   26  332
     4  908  937  728
2    0   88  592  902
     1  363  121  274
     2  688  509  770
     3  424  178  642
     4  809   28  442
3    0  172  932  263
     1  334  359  816
     2  290  856  584
     3  955   42  938
     4  832  220  348

这篇关于如何在python中将3d数组转换为数据框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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