Passing only specified columns to Pandas dataframe from list of lists

Viewed 134

I have the following list of lists in Python

myList = [datetime.datetime(2020, 5, 16, 0, 15), '9387.95000000', '9418.96000000', '9386.22000000', '9406.76000000', '138.33460500', 1589581199999, '1300408.00793448', 2156, '88.84298900', '835174.15438128', '0'], [datetime.datetime(2020, 5, 16, 0, 20), '9407.03000000', '9437.65000000', '9405.96000000', '9429.36000000', '190.78911000', 1589581499999, '1797685.31006086', 2454, '100.00883200', '942460.13231483', '0', ...]

I'm trying to create a Pandas dataframe from it, here is what i tried:

df = pd.DataFrame(Result, columns=['Date', 'Open', 'High', 'Low', 'Close', 'Volume'])

This will give me the following error:

AssertionError: 6 columns passed, passed data had 12 columns

How can i pass only the first 6 elements of the list of lists to the dataframe, so that i won't get the error? Thanks in advance!

1 Answers

Filter first 6 values in list comprehension:

df = pd.DataFrame([x[:6] for x in myList], 
                  columns=['Date', 'Open', 'High', 'Low', 'Close', 'Volume'])
print (df)
                 Date           Open           High            Low  \
0 2020-05-16 00:15:00  9387.95000000  9418.96000000  9386.22000000   
1 2020-05-16 00:20:00  9407.03000000  9437.65000000  9405.96000000   

           Close        Volume  
0  9406.76000000  138.33460500  
1  9429.36000000  190.78911000  
Related