简体   繁体   中英

Create Panda DataFrame from Nested List

I'm trying to create a panda dataframe from nested list that contains ndarray inside below:

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 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.

Please help.

Thx in advance.

The pd.DataFrame constructor accepts a list of lists directly. There is no need to redefine list elements as numpy arrays.

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

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

print(df)

#    D0  D1
# 0   1   2
# 1   2   3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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