将数组列表转换为pandas datafram

2024-05-20 00:01:26 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个numpy数组列表,正试图将其转换为DataFrame。每个数组都应该是dataframe的一行。

使用pd.DataFrame()不起作用。它总是给出错误:ValueError:必须传递二维输入。

有更好的办法吗?

这是我当前的代码:

list_arrays = array([[0, 0, 0, 1, 0, 0, 0, 0, 00]], dtype=uint8), array([[0, 0, 3, 2, 0, 0, 0, 0, 00]], dtype=uint8)]

d = pd.DataFrame(list_of_arrays)

ValueError: Must pass 2-d input

Tags: numpydataframe列表错误数组arraylistpd
3条回答

这是一条路。

import numpy as np, pandas as pd

lst = [np.array([[0, 0, 0, 1, 0, 0, 0, 0, 0]], dtype=int),
       np.array([[0, 0, 3, 2, 0, 0, 0, 0, 0]], dtype=int)]

df = pd.DataFrame(np.vstack(lst))

#    0  1  2  3  4  5  6  7  8
# 0  0  0  0  1  0  0  0  0  0
# 1  0  0  3  2  0  0  0  0  0

Alt 1

pd.DataFrame(sum(map(list, list_arrays), []))

   0  1  2  3  4  5  6  7  8
0  0  0  0  1  0  0  0  0  0
1  0  0  3  2  0  0  0  0  0

Alt 2

pd.DataFrame(np.row_stack(list_arrays))

   0  1  2  3  4  5  6  7  8
0  0  0  0  1  0  0  0  0  0
1  0  0  3  2  0  0  0  0  0

选项1:

In [143]: pd.DataFrame(np.concatenate(list_arrays))
Out[143]:
   0  1  2  3  4  5  6  7  8
0  0  0  0  1  0  0  0  0  0
1  0  0  3  2  0  0  0  0  0

选项2:

In [144]: pd.DataFrame(list(map(np.ravel, list_arrays)))
Out[144]:
   0  1  2  3  4  5  6  7  8
0  0  0  0  1  0  0  0  0  0
1  0  0  3  2  0  0  0  0  0

Why do I get:

ValueError: Must pass 2-d input

我认为pd.DataFrame()试图将其转换为NDArray,如下所示:

In [148]: np.array(list_arrays)
Out[148]:
array([[[0, 0, 0, 1, 0, 0, 0, 0, 0]],

       [[0, 0, 3, 2, 0, 0, 0, 0, 0]]], dtype=uint8)

In [149]: np.array(list_arrays).shape
Out[149]: (2, 1, 9)     # <----- NOTE: 3D array

相关问题 更多 >