Reputation: 34
I have a list of tuples that I want to convert to pandas data frame and write to excel with column headers.
Column_headers = ["Name", "Count1", "Count2"]
mylist = [('A',(1,2)), ('B',(23,2)), ('C',(1,23)), ('D',(5,23))]
Output in Excel
Name | Count1 | Count2
A | 1 | 2
B | 23 | 2
C | 1 | 23
D | 5 | 23
I tried below but it only saves the last entry in mylist.
writer = pd.ExcelWriter('demo.xlsx', engine='xlsxwriter')
start_row = 0
for i, data in enumerate(mylist):
df = pd.DataFrame({"Name": [data[0]],
"Count1": [data[1][0]],
"Count2": [data[1][1]]})
df.to_excel(writer, sheet_name='Sheet1',header=True, index=False)
writer.save()
Can someone please provide any pointers?
Thanks in advance and Happy Holidays
Upvotes: 1
Views: 142
Reputation: 20689
You can use itertools.chain.from_iterable
here
from itertools import chain
df = pd.DataFrame(map(chain.from_iterable, mylist), columns=Column_headers)
Name Count1 Count2
0 A 1 2
1 B 23 2
2 C 1 23
3 D 5 23
Upvotes: 2
Reputation: 71620
Try the below code:
Column_headers = ["Name", "Count1", "Count2"]
mylist = [('A',(1,2)), ('B',(23,2)), ('C',(1,23)), ('D',(5,23))]
df = pd.DataFrame([[i[0], i[1][0], i[1][1]] for i in mylist], columns=Column_headers)
df.to_excel('demo.xlsx')
Upvotes: 1