简体   繁体   English

如何将 ndarray 转换为 pandas DataFrame |python|pandas|numpy|

[英]How to convert ndarray to a pandas DataFrame |python|pandas|numpy|

I'm trying to convert my numpy array into a dataframe,我正在尝试将我的 numpy 数组转换为 dataframe,

array:大批:

array([[[9.447859e+06, 3.000000e+00, 1.350000e+01, 7.000000e+00]]

   [[9.447859e+06, 2.000000e+00, 1.350000e+01, 4.000000e+00]],

   [[9.447859e+06, 1.000000e+00, 1.350000e+01, 7.000000e+00]]])

expected output:预期 output:

A            B            C            D
9.447859e+06 3.000000e+00 1.350000e+01 7.000000e+00
9.447859e+06 2.000000e+00 1.350000e+01 4.000000e+00
9.447859e+06 1.000000e+00 1.350000e+01 7.000000e+00

can I get a solution for this?我可以为此找到解决方案吗? Thanks.谢谢。

You can use numpy.squeeze() to remove axes of length one from array.您可以使用numpy.squeeze()从数组中删除长度为 1 的轴。

df = pd.DataFrame(np.squeeze(data), columns=['A', 'B', 'C', 'D'])

Try this尝试这个

import numpy as np
a = np.array([[[1, 2,3, 4]], [[5, 6, 7, 8]]])

m,n,r = a.shape
out_arr = a.reshape(m*n,-1)
out_df = pd.DataFrame(out_arr,columns =['A','B','C','D'])
out_df

Result结果

    A   B   C   D
0   1   2   3   4
1   5   6   7   8

You can specify which part of the array to use as data:您可以指定将数组的哪一部分用作数据:

pd.DataFrame(data=a[:,0], index=range(0, len(a)), columns=['A', 'B', 'C', 'D'])

This works (after removing the double brackets):这有效(删除双括号后):

import pandas as pd
import numpy as np
a = np.array([[9.447859e+06, 3.000000e+00, 1.350000e+01, 7.000000e+00],

   [9.447859e+06, 2.000000e+00, 1.350000e+01, 4.000000e+00],

   [9.447859e+06, 1.000000e+00, 1.350000e+01, 7.000000e+00]])

b = pd.DataFrame(data=a )
b

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

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