简体   繁体   English

从嵌套列表创建Panda DataFrame

[英]Create Panda DataFrame from Nested List

I'm trying to create a panda dataframe from nested list that contains ndarray inside below: 我正在尝试从下面包含ndarray的嵌套列表中创建一个熊猫数据框:

from numpy import array
a = list([[1,2],[2,3]])                  
a[0] = array([[1,2]])
a[0][0] = array([1,2])

what I want to achieve is below: 我要实现的目标如下:

 D0    D1  
 1     2   
 2     3

I've tried just using 我已经尝试过使用

pd.DataFrame(a)

which creates 这创造了

   D0      
 [1,2]        
 [2,3]     

I also tried using pd.append inside the for loop 我也尝试在for循环中使用pd.append

for i in range(0, len(a)):
  df = df.append(pd.DataFrame(a[i]))

which achieves what I want but it's extremely slow and somehow the df.append creates duplicates. 这实现了我想要的,但是它非常慢,并且df.append以某种方式创建了重复项。

Please help. 请帮忙。

Thx in advance. 提前谢谢。

The pd.DataFrame constructor accepts a list of lists directly. pd.DataFrame构造函数直接接受列表列表。 There is no need to redefine list elements as numpy arrays. 无需将列表元素重新定义为numpy数组。

a = [[1,2],[2,3]]

df = pd.DataFrame(a, columns=['D0', 'D1'])

print(df)

#    D0  D1
# 0   1   2
# 1   2   3

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

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