Home > Mobile >  Converting a csv file generated in jupyter notebook into list of tuples
Converting a csv file generated in jupyter notebook into list of tuples

Time:11-23

i am doing an exercise on the candidate elimination algorithm. I got a JSON file, i converted it to csv file using the following code

step 1: pdobj=pd.read_json('xxx.json', orient = 'records') print(pdobj)

step 2: csvData=pdobj.to_csv(index=False) print(csvData)

However when i am trying to convert this file into list of tuples i am getting errors i dont want to save the file in my disk then import it again. I just want to convert the csv file i generated directly into list of tuples.

this code landed me in error

with open (csvData) as csvfile:
      examples =[tuple(line) for line in csv.reader(csvfile)]

CodePudding user response:

The open() function takes the CSV file name as a parameter but not the CSV data itself. So, there is no need to read the CSV data again as it is already available as a string in the csvData variable.

To convert the CSV data into a list of tuples, use the following code. The conversion part was adopted from this Stack thread.

Input JSON file:

[
  {"Series":"I", "X":10.0, "Y":8.04},
  {"Series":"I", "X":8.0, "Y":6.95},
  {"Series":"I", "X":13.0, "Y":7.58},
  {"Series":"I", "X":9.0, "Y":8.81},
  {"Series":"I", "X":11.0, "Y":8.33}
]
# Start of your code

pdobj=pd.read_json('sample_data/anscombe.json', orient = 'records') 
print(type(pdobj)) 

csvData=pdobj.to_csv(index=False, header=False) # I have skipped the header of the CSV
print(type(csvData))

# End of your code


# Convert the CSV data to a list of tuples
lot = [tuple(line.split(",")) for line in csvData.split('\n')]
print(list_of_tuples)

Output of the above code:

[('I', '10', '8.04'), ('I', '8', '6.95'), ('I', '13', '7.58'), ('I', '9', '8.81'), ('I', '11', '8.33')]
  • Related