[英]Convert list of arrays to pandas dataframe
I have a list of numpy arrays that I'm trying to convert to DataFrame.我有一个要转换为 DataFrame 的 numpy 数组列表。 Each array should be a row of the dataframe.
每个数组应该是数据帧的一行。
Using pd.DataFrame() isn't working.使用 pd.DataFrame() 不起作用。 It always gives the error: ValueError: Must pass 2-d input.
它总是给出错误:ValueError: Must pass 2-d input。
Is there a better way to do this?有没有更好的方法来做到这一点?
This is my current code:这是我当前的代码:
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_arrays)
ValueError: Must pass 2-d input
Option 1:选项 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
Option 2:选项 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
I think pd.DataFrame()
tries to convert it to NDArray like as follows:我认为
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
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
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
Here is one way.这是一种方法。
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
You can using pd.Series
您可以使用
pd.Series
pd.Series(l).apply(lambda x : pd.Series(x[0]))
Out[294]:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.