I made this code that allows me to create a table in an excel file. Only I wanted to add at the beginning of the column a string and then afterwards attach a list of elements to it.
def CreateExcel(metric,consumo, writer):
df = pd.DataFrame({
'metricID': metric,
'consumo' : consumo,
})
df = df.sort_values('consumo', ascending=False)
df.to_excel(writer, sheet_name="foglio1", startrow=1, header=False, index=False)
workbook = writer.book
worksheet = writer.sheets["foglio1"]
(max_row, max_col) = df.shape
column_settings = [{"header":column} for column in df.columns]
worksheet.add_table(0, 0, max_row, max_col - 1, {"columns":column_settings})
worksheet.set_column(0, max_col - 1, 70)
this is the working code, but I would like to add a string like this
df = pd.DataFrame({
'metricID': "timeframe" + metric,
'consumo' : "2022-11-10 2022-12-10" + consumo,
})
python does not give me a syntax error, but in running the code it gives me this error:
'metricID': "timeframe" + metric,
~~~~~~~~~~~~^~~~~~~
TypeError: can only concatenate str (not "list") to str
keeping in mind that the elements in the list are sorted in the function later on, I need to have those two strings be at the beginning of the table, so that then they are not put randomly in the list
>Solution :
We cannot reproduce without actual data, but I understand your question such that consumo and metric are lists that you want to extend by strings. So this is not a problem with pandas but a general one:
s = "hello"
l = ["world"]
result = [s] + l # concatenate the string (as a list) with an existing list
print(result) # ["hello", "world"]
so the changes in your code are only subtle. Note that I added the list brackets to turn your string into a list.
def CreateExcel(metric,consumo, writer):
df = pd.DataFrame({
'metricID': ["timeframe"] + metric,
'consumo' : ["2022-11-10 2022-12-10"] + consumo,
})
df = df.sort_values('consumo', ascending=False)
df.to_excel(writer, sheet_name="foglio1", startrow=1, header=False, index=False)
workbook = writer.book
worksheet = writer.sheets["foglio1"]
(max_row, max_col) = df.shape
column_settings = [{"header":column} for column in df.columns]
worksheet.add_table(0, 0, max_row, max_col - 1, {"columns":column_settings})
worksheet.set_column(0, max_col - 1, 70)