Reputation: 19
I'm working on code were I read data from an existed text file, then I'm trying to write it inside an Excel file by creating a new one.
distance_matrix.txt
[0]
[1, 0]
[13, 12, 0]
[17, 16, 10, 0]
[16, 15, 8, 1, 0]
[13, 12, 4, 5, 4, 0]
[12, 11, 6, 11, 10, 6, 0]
I first opened the text file then read it and stored it in a list.
file1 = open("distance_matrix.txt", "r")
contents1 = file1.readlines()
Then I have stored contents1 in another list (I'm not sure if it's really a list because when I print it I only get the last line!).
import re
numbers = []
for i in contents1:
numbers = re.split(', |\[|\]', i)
numbers.remove('')
numbers.remove('\n')
for i in numbers:
print(numbers[0])
df = pd.DataFrame(
{#"A":numbers}
)
writer = ExcelWriter("MyData.xls")
df.to_excel(writer,"sheet1", index = False)
writer.save()
My question is how would I write this triangle shape inside the Excel file with a header to each column after taking those numbers from the text file?
A B C D E F G
[0]
[1, 0]
[13, 12, 0]
[17, 16, 10, 0]
[16, 15, 8, 1, 0]
[13, 12, 4, 5, 4, 0]
[12, 11, 6, 11, 10, 6, 0]
Upvotes: 0
Views: 69
Reputation: 709
by default the headers are True
,
DataFrame.to_excel(self, excel_writer, sheet_name='Sheet1', na_rep='', float_format=None, columns=None, header=True, index=True, index_label=None, startrow=0, startcol=0, engine=None, merge_cells=True, encoding=None, inf_rep='inf', verbose=True, freeze_panes=None)
,
Try adding header=False
df = pd.DataFrame(
{#"A":numbers}
)
writer = ExcelWriter("MyData.xls")
df.to_excel(writer,"sheet1", index = False, header=False)
writer.save()
Upvotes: 1