Skip to content
Advertisement

Python Import Excel List

I have the following list in Python:

list = [[1, (200, 45)], [2, (53, 543)], [3, (5, 5)], [4,(655, 6456464)],[5, (64564, 45)], [6, (6, 5445)], [7, (546, 46)], [8, (64, 645)]

I now want to save these into an Excel and then read them in. How can I do this? I have not found such a “simple” import with Google, mostly it is more complex imports of Excel files.

Thanks

Serpiente32

Advertisement

Answer

Here is a sample code:

import pandas as pd

list_ = [[1, (200, 45)], [2, (53, 543)], [3, (5, 5)], [4,(655, 6456464)],[5, (64564, 45)], [6, (6, 5445)], [7, (546, 46)], [8, (64, 645)]]
list_ = [[item[0], *item[1]] for item in list_]
# The line above just unpacks the tuple and makes every element a list of 3 numbers

pd.DataFrame(data=list_).to_excel("data.xlsx", index=False) # save in excel
# you now have an excel file in same folder with three columns

data = pd.read_excel("data.xlsx")  # read back from excel
print(data)

Output:

   0      1        2
0  1    200       45
1  2     53      543
2  3      5        5
3  4    655  6456464
4  5  64564       45
5  6      6     5445
6  7    546       46
7  8     64      645

Note: You should never use reserved keywords like list as label names. Can cause unexpected issues in your programs.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement