简体   繁体   English

从不同大小的numpy数组创建熊猫数据框

[英]create pandas dataframe from different size numpy arrays

I have the following numpy arrays which are of different shape. 我有以下不同形状的numpy数组。 I want to use pandas to create a dataframe so that I can display it neatly as shown below: 我想使用熊猫创建一个数据框,以便可以整齐地显示它,如下所示:

numpy arrays: 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.        ]]

resulting dataframe: 结果数据框:

在此处输入图片说明

One way is to loop around among all 3 arrays and collect based on the index. 一种方法是在所有3个数组之间循环并根据索引进行收集。 I have tried numpy.column_stack and zip and map to some extent but to not the desired result. 我尝试了numpy.column_stack和zip并映射到一定程度,但没有达到期望的结果。

I always have used pandas dataframe to display results and it was easy. 我一直使用pandas数据框来显示结果,这很容易。 This one seems a little tricky. 这似乎有些棘手。 How can I achieve this. 我该如何实现。

If you have put the arrays into a dict data , you can loop over keys and add as you go: 如果已将数组放入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

Alternately, you can mash it all together by hand, but that's less scalable: 或者,您可以将它们手工融合在一起,但是扩展性较差:

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"]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM