首页 > 开发 > Python > 正文

Python实现把多维数组展开成DataFrame

2024-09-09 19:02:52
字体:
来源:转载
供稿:网友

如下所示:

import numpy as npimport pandas as pd################# 准备数据 #################a1 = np.arange(1,101)a3 = a1.reshape((2,5,10))a3'''array([[[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10],  [ 11, 12, 13, 14, 15, 16, 17, 18, 19, 20],  [ 21, 22, 23, 24, 25, 26, 27, 28, 29, 30],  [ 31, 32, 33, 34, 35, 36, 37, 38, 39, 40],  [ 41, 42, 43, 44, 45, 46, 47, 48, 49, 50]],    [[ 51, 52, 53, 54, 55, 56, 57, 58, 59, 60],  [ 61, 62, 63, 64, 65, 66, 67, 68, 69, 70],  [ 71, 72, 73, 74, 75, 76, 77, 78, 79, 80],  [ 81, 82, 83, 84, 85, 86, 87, 88, 89, 90],  [ 91, 92, 93, 94, 95, 96, 97, 98, 99, 100]]])'''################# 准备标签 ################## 第 1 维的标签index1 = pd.Series(np.arange(1,11))index1 = index1.astype(str)index1 = 'A'+index1index1'''0  A11  A22  A33  A44  A55  A66  A77  A88  A99 A10'''# 第 2 维的标签index2 = pd.Series(np.arange(1,6))index2 = index2.astype(str)index2 = 'B'+index2index2'''0 B11 B22 B33 B44 B5'''# 第 3 维的标签index3 = pd.Series(np.arange(1,3))index3 = index3.astype(str)index3 = 'C'+index3index3'''0 C11 C2'''################# 展开数据 ################## 把三维数组展开value = a3.flatten()value = pd.Series(value)value.name = 'value'value'''0  11  22  3  ... 97  9898  9999 100Name: value, Length: 100, dtype: int64'''################# 展开标签 #################import itertools# index的笛卡尔乘积。注意:高维在前,低维在后prod = itertools.product(index3, index2, index1 )# 转换为DataFrameprod = pd.DataFrame([x for x in prod])prod.columns = ['C', 'B', 'A']prod.T''' 0 1 2 3 4 5 6 7 8 9 ... 90 91 92 93 94 95 96 /C C1 C1 C1 C1 C1 C1 C1 C1 C1 C1 ... C2 C2 C2 C2 C2 C2 C2 B B1 B1 B1 B1 B1 B1 B1 B1 B1 B1 ... B5 B5 B5 B5 B5 B5 B5 A A1 A2 A3 A4 A5 A6 A7 A8 A9 A10 ... A1 A2 A3 A4 A5 A6 A7  97 98 99 C C2 C2 C2 B B5 B5 B5 A A8 A9 A10 [3 rows x 100 columns]'''################# 最终数据 ################## 合并成一个DataFramepd.concat([prod, value], axis=1)'''  C B A value0 C1 B1 A1  11 C1 B1 A2  22 C1 B1 A3  33 C1 B1 A4  44 C1 B1 A5  55 C1 B1 A6  66 C1 B1 A7  77 C1 B1 A8  88 C1 B1 A9  99 C1 B1 A10  1010 C1 B2 A1  1111 C1 B2 A2  1212 C1 B2 A3  1313 C1 B2 A4  1414 C1 B2 A5  1515 C1 B2 A6  1616 C1 B2 A7  1717 C1 B2 A8  1818 C1 B2 A9  1919 C1 B2 A10  2020 C1 B3 A1  2121 C1 B3 A2  2222 C1 B3 A3  2323 C1 B3 A4  2424 C1 B3 A5  2525 C1 B3 A6  2626 C1 B3 A7  2727 C1 B3 A8  2828 C1 B3 A9  2929 C1 B3 A10  30.. .. .. ... ...70 C2 B3 A1  7171 C2 B3 A2  7272 C2 B3 A3  7373 C2 B3 A4  7474 C2 B3 A5  7575 C2 B3 A6  7676 C2 B3 A7  7777 C2 B3 A8  7878 C2 B3 A9  7979 C2 B3 A10  8080 C2 B4 A1  8181 C2 B4 A2  8282 C2 B4 A3  8383 C2 B4 A4  8484 C2 B4 A5  8585 C2 B4 A6  8686 C2 B4 A7  8787 C2 B4 A8  8888 C2 B4 A9  8989 C2 B4 A10  9090 C2 B5 A1  9191 C2 B5 A2  9292 C2 B5 A3  9393 C2 B5 A4  9494 C2 B5 A5  9595 C2 B5 A6  9696 C2 B5 A7  9797 C2 B5 A8  9898 C2 B5 A9  9999 C2 B5 A10 100[100 rows x 4 columns]'''

以上这篇Python实现把多维数组展开成DataFrame就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网之家。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表