将数组列表获取到Pandas数据框中 [英] Getting a list of arrays into a Pandas dataframe
问题描述
所以我在Python中有一个数组列表: [[0,1,0,1],[1,0,1,1],[0,1,1,1]]
。我想将此数组列表做成Pandas数据框,每个数组都是一行。有没有办法在Python中快速轻松地做到这一点?我试过 values = np.split(values,len(values))
将数组列表拆分成多个数组(嗯,我试过了)。然后尝试使用 df = pd.DataFrame(values)
创建一个数据框。但这是我的错误出处。我收到必须通过二维输入错误消息。知道我在做什么错以及如何解决吗?或更简单的方法来解决这个问题?谢谢!
So I have a list of arrays in Python: [[0, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1]]
. I would like to make this list of arrays into a Pandas dataframe, with each array being a row. Is there a way to do this quickly and easily in Python? I tried values = np.split(values, len(values))
to split the list of arrays into multiple arrays (well, I tried). And then tried to create a dataframe with df = pd.DataFrame(values)
. But this is where my error came from. I got a "must pass 2-d input" error message. Any idea what I'm doing wrong and how to fix it? Or an easier way to go about this? Thanks!
推荐答案
无需进行所有拆分,等等。如果您将其作为二维列表的列表(意味着所有行具有相同数量的元素),只需将其传递给 DataFrame
构造函数即可:
No need to do all that splitting, etc. If you have it as a list of lists that is two dimensional (meaning all rows have the same number of elements), you can simply pass it to the DataFrame
constructor:
data = [[0, 1, 0, 1], [1, 0, 1, 1], [0, 1, 1, 1]]
pd.DataFrame(data)
生成期望值:
>>> pd.DataFrame(data)
0 1 2 3
0 0 1 0 1
1 1 0 1 1
2 0 1 1 1
这篇关于将数组列表获取到Pandas数据框中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!