将 jupyter notebook 中生成的 csv 文件转换为元组列表

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

我正在做候选淘汰算法的练习。我得到了一个 JSON 文件,我使用以下代码将其转换为 csv 文件

第一步: pdobj=pd.read_json('xxx.json', orient = 'records') print(pdobj)

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

但是,当我尝试将此文件转换为元组列表时出现错误,我不想将该文件保存在我的磁盘中然后再次导入它。我只想将我生成的 csv 文件直接转换成元组列表。

这段代码让我犯了错误

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

open() 函数将 CSV 文件名作为参数而不是 CSV 数据本身。因此,无需再次读取 CSV 数据,因为它已在 csvData 变量中作为字符串提供。

要将 CSV 数据转换为元组列表,请使用以下代码。转换部分取自这个Stack thread.

输入JSON文件:

[
  {"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)

以上代码的输出:

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