简体   繁体   中英

How to save a tuple to excel in python

I have fetched some data from an application and the output is in tuple.

deals

(   

  Instrument Date Announced  SDC Deal No
 0  154085693165     2020-07-16   3577020040
 1  154086829977     2020-07-16   3603239040
 2  154086830011     2020-07-16   3603259040
 3  154086830078     2020-07-16   3603284040
 4  154086830341     2020-07-16   3603413040,
 None)

How do i save this to an xlsx file using python?

The tuple returns 2 values. One with the data frame and other with any error. In this case. So the below code helps.

datframe,error=ek.function_name(argument1,argument2,...)

or,

deals,e=ek.get_data(common_name,company_id)

So now

print(deals) returns

Instrument Date Announced  SDC Deal No
 0  154085693165     2020-07-16   3577020040
 1  154086829977     2020-07-16   3603239040
 2  154086830011     2020-07-16   3603259040
 3  154086830078     2020-07-16   3603284040
 4  154086830341     2020-07-16   3603413040

and print(e) returns

none
import csv

deals = list(deals)

with open("NameOfFile.csv",  "w") as csvfile:
    write = csv.writer(csvfile)
    
    for x in deals:
        write.writerow(map(lambda x: [x], deals))

This should work. This is taken (slightly modified) from csv docs for Python.

import pandas as pd
df = pd.DataFrame(deals)
df.head()

Can you see what you get from this? After you editted your index and columns, you can run:

df.to_excel('name.xls')

You may try something like below code to write a list of string in a csv file:

import numpy as np
import pandas as pd

deals = ("Instrument", "Date", "Announced",  "SDC", "Deal", "No")

x = []
for j in range(0,len(deals)):
    x.append(str(deals[j]))

with open("myfile.txt", "w") as file1:
    for i in range(0,len(x)):
        file1.write(x[i])

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM