【问题标题】:Save an array in a cell in csv file将数组保存在 csv 文件的单元格中
【发布时间】:2020-07-02 05:29:28
【问题描述】:

我想将 [1,2,3,4] 之类的数字数组写入 csv 文件的单元格中。

我的 csv 文件应该是这样的

 Title        array 

'file1' ,  '[1,2,3,4]'

'file2'  , '[3,4,5,6]'

'file3'  , '[6,8,2,9]'

我想这样做,因为我想将此 csv 文件保存在 mysql 数据库中。 这样我以后可以从数据库中检索数据。

谁能解释一下如何用python写这个。 谢谢。

【问题讨论】:

    标签: python python-3.x pandas python-2.7 dataframe


    【解决方案1】:

    因此,对于您的测试数据,您可以这样做

    import csv
    with open('example.csv', 'w', newline='') as csvfile:
        csvwriter = csv.writer(csvfile, delimiter=',',escapechar=' ', quoting=csv.QUOTE_NONE)
        csvwriter.writerow(['file1' , '[1,2,3,4]'])
        csvwriter.writerow(['file2' , '[3,4,5,6]'])
        csvwriter.writerow(['file3' , '[6,8,2,9]'])
    

    使用此代码,我可以创建一个您所描述的 csv 文件。

    【讨论】:

      【解决方案2】:
      import pandas as pd
      import csv
      sample=[[1,2,3,4],[3,4,5,6],[6,8,2,9]]
      fileName=['file1','file2','file3']
      df=pd.Series(sample)
      df = df.to_frame()
      df.rename(columns = {0:'Array'}, inplace = True)
      df['Title']=fileName
      cols = ['Title','Array']
      df = df[cols]
      df.to_csv('file1.csv',index=False)
      

      【讨论】:

        【解决方案3】:

        不太确定我是否完全理解了这个问题。默认情况下,CSV 文件会将逗号分隔的值作为单个单元格读取,因此您的输出可能类似于: 'file1' , '[1, 2, 3, 4]' 这将导致 5 列,除非您更改分隔符或解析它的方式。

        但是要获得像你建议的输出,像下面这样的简单程序就可以了:

        f = open('out.csv', 'w+')
        f.write("Title, array\n")
        f.write("{0}, {1}".format(file_name, array_def))
        f.close()
        

        例如在哪里

        file_name = 'file1'
        array_def = [1,2,3,4]
        

        希望对您有所帮助。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2021-10-04
          • 1970-01-01
          • 1970-01-01
          • 2022-12-23
          • 2014-11-25
          • 2021-05-28
          • 2021-11-28
          相关资源
          最近更新 更多