Joe Dobrow
Joe Dobrow

Reputation: 9

Faster way of iterating through lists in Python

I have list vector_list of length 800,000, where the elements are lists of size 768. I'm trying to add 768 columns to a pandas dataframe where each column is 800,000 long and represents an element from each list. Here's my code:

active = pd.DataFrame()    
for i in range(len(vector_list[0])):
    element_list = []
    for j in range(len(vector_list)):
        element_list.append(vector_list[j][i])
    active['Element {}'.format(i)] = element_list

Just to reiterate,

len(vector_list) = 800,000
len(vector_list[0]) = 768

Is there a more clever, faster way to do this?

Upvotes: 1

Views: 72

Answers (1)

Ajay Dabas
Ajay Dabas

Reputation: 1444

Directly pass the list to DataFrame constructor.

import pandas as pd
_list = [[1, 2], [3, 4], [5, 6], [7, 8]] 
df = pd.DataFrame(_list) 
print(df.head())

Output

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

Upvotes: 3

Related Questions