从不同大小的numpy数组创建pandas数据帧

问题描述 投票:1回答:1

我有以下numpy数组,形状各异。我想使用pandas创建一个数据帧,以便我可以整齐地显示它,如下所示:

numpy数组:

et_arr:  [  8.94668401e+01   1.66449935e+01  -4.44089210e-14]
ea_arr:  [ 100.           21.84087363    1.04031209]
it: 
[[ 0.1728      1.0688      1.4848      1.6008    ]
 [ 1.36746667  1.62346667  1.63946667  0.        ]
 [ 1.64053333  1.64053333  0.          0.        ]
 [ 1.64053333  0.          0.          0.        ]]

结果数据帧:

enter image description here

一种方法是在所有3个阵列中循环并基于索引收集。我已经尝试过numpy.column_stack和zip并在某种程度上映射但不是想要的结果。

我总是使用pandas数据帧来显示结果,这很容易。这个看起来有点棘手。我怎样才能做到这一点。

python arrays python-3.x pandas numpy
1个回答
2
投票

如果您已将数组放入dict data,则可以循环键并随意添加:

data = {"et_arr":[8.94668401e+01,1.66449935e+01,-4.44089210e-14],
        "ea_arr":[100.,21.84087363,1.04031209],
        "it":[[0.1728,1.0688,1.4848,1.6008],
              [1.36746667,1.62346667,1.63946667,0.],
              [1.64053333,1.64053333,0.,0.],
              [1.64053333,0.,0.,0.]]}

# To keep track of the order of dict indices we'll capture them as we loop:
indices = []
df = pd.DataFrame()

for k in data.keys():
    df = pd.concat([df, pd.DataFrame(data[k]).T], ignore_index=True).fillna(0)
    if k == "it":
        indices.extend([f"n={i+1}" for i in range(len(data[k]))])
    else:
        indices.append(k)

df.index = indices
df.columns = df.columns + 1

df
                1          2             3         4
et_arr   89.46684  16.644994 -4.440892e-14  0.000000
ea_arr  100.00000  21.840874  1.040312e+00  0.000000
n=1       0.17280   1.367467  1.640533e+00  1.640533
n=2       1.06880   1.623467  1.640533e+00  0.000000
n=3       1.48480   1.639467  0.000000e+00  0.000000
n=4       1.60080   0.000000  0.000000e+00  0.000000

或者,您可以手动将它们全部混合在一起,但可扩展性较差:

df = pd.DataFrame(it)
arr_df = pd.DataFrame([et_arr,ea_arr])
df = pd.concat([df, arr_df], ignore_index=True).fillna(0)
df.columns = range(1,5)
df.columns.name = "iter"
df.index = ["n=1","n=2","n=3","n=4","et","ea"]
© www.soinside.com 2019 - 2024. All rights reserved.