简体   繁体   English

3维numpy数组到熊猫数据框

[英]3 dimensional numpy array to pandas dataframe

I have a 3 dimensional numpy array 我有一个3维的numpy数组

   ([[[0.30706802]],

   [[0.19451728]],

   [[0.19380492]],

   [[0.23329106]],

   [[0.23849282]],

   [[0.27154338]],

   [[0.2616704 ]], ... ])

with shape (844,1,1) resulting from RNN model.predict() 具有RNN模型产生的形状(844,1,1).predict()

y_prob = loaded_model.predict(X) y_prob = load_model.predict(X)

, my problem is how to convert it to a pandas dataframe. ,我的问题是如何将其转换为熊猫数据框。 I have used Keras 我用过Keras

my objective is to have this: 我的目标是:

0      0.30706802
7      0.19451728
21     0.19380492
35     0.23329106
42       ...
         ...   
815      ...
822      ...
829      ...
836      ...
843      ...
Name: feature, Length: 78, dtype: float32

idea is to first flatten the nested list to list than convert it in df using from_records method of pandas dataframe 想法是首先将嵌套列表展平到列表,然后使用from_records方法在df from_records其转换

import numpy as np
import pandas as pd

data = np.array([[[0.30706802]],[[0.19451728]],[[0.19380492]],[[0.23329106]],[[0.23849282]],[[0.27154338]],[[0.2616704 ]]])

import itertools
data  = list(itertools.chain(*data))
df = pd.DataFrame.from_records(data)

Without itertools 没有itertools

data = [i for j in data for i in j]
df = pd.DataFrame.from_records(data)

Or you can use flatten() method as mentioned in one of the answer, but you can directly use it like this 或者您可以使用答案之一中提到的flatten()方法,但是您可以像这样直接使用它

pd.DataFrame(data.flatten(),columns = ['col1']) 

Here you go! 干得好!

import pandas as pd
y = ([[[[11]],[[13]],[[14]],[[15]]]])
a = []
for i in y[0]:
    a.append(i[0])
df = pd.DataFrame(a)
print(df)

Output: 输出:

    0
0  11
1  13
2  14
3  15

Feel free to set your custom index values both for axis=0 and axis=1. 随时为axis = 0和axis = 1设置自定义索引值。

You could try: 您可以尝试:

s = pd.Series(your_array.flatten(), name='feature')

https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html https://docs.scipy.org/doc/numpy/reference/generated/numpy.ndarray.flatten.html

You can then convert the series to a dataframe using s.to_frame() 然后,您可以使用s.to_frame()将系列转换为数据s.to_frame()

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

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