【问题标题】:Pandas how to save a list to csv熊猫如何将列表保存到csv
【发布时间】:2020-10-09 02:58:10
【问题描述】:

我在 pandas 中有一个列表,我想将它写入一个 csv 文件,其中每个元素都是一个新行。

    list3= ["France","Germany","USA"]
    with open('your_file.csv', 'w') as f:
        f.write(str(list3))

但是输出是水平的而不是垂直的,如果有人知道如何去掉输出中的引号,我也会很感激。

用我上面的代码输出:

我想要的输出:

【问题讨论】:

  • 这能回答你的问题吗? Create a .csv file with values from a Python list
  • 您可以发布示例输出吗?你想要 3 行,每行都有一个国家名称?
  • @ATOMP - 如果我没看错 OP,应该有 3 行输出。
  • @tdelaney 很高兴您回答了这个问题。链接这个是因为它基本上是同一个问题,如果没有人决定回答不希望 OP 仍然被卡住。
  • @ATOMP - 您的链接在 99% 的情况下都是正确的,但它只写了一行。我认为 OP 想要 3 行。如果写问题的人添加示例输出会很棒,但是,嘿,我猜他们喜欢让我们猜测。

标签: python pandas jupyter


【解决方案1】:

这是一个 Python 列表,看不到 pandas

In [26]: list3= ["France","Germany","USA"]                                      

看看str 产生了什么:

In [27]: str(list3)                                                             
Out[27]: "['France', 'Germany', 'USA']"

那是一个带括号和引号的字符串。

你想要的更像:

In [28]: for word in list3: print(word)                                         
France
Germany
USA

或将其写入文件:

In [29]: with open('txt', 'w') as f: 
    ...:     for word in list3: 
    ...:         f.write('%s\n'%word) 
    ...:                                                                        
In [30]: cat txt                                                                
France
Germany
USA

或者用printfile参数:

In [31]: with open('txt', 'w') as f: 
    ...:     for word in list3: 
    ...:         print(word, file=f) 

或者你可以加入字符串换行符:

In [33]: '\n'.join(list3)                                                       
Out[33]: 'France\nGermany\nUSA'
In [34]: with open('txt', 'w') as f: 
    ...:     print('\n'.join(list3), file=f) 

您可以将列表放在pandas DataFrame 中,但是在编写 csv 时您必须关闭列和索引。

numpy 也可以使用 np.savetxt('txt',list3, fmt='%s')

将这种基本字符串列表写入文件的方法有很多种。一些基本的,一些使用更强大的编写器。

【讨论】:

    【解决方案2】:

    这可以通过 CSV 模块完成。每行必须是一个列表,但您可以为 csv 编写器生成它们,列表中的每个项目一个

    import csv
    list3= ["France","Germany","USA"]
    with open('your_file.csv', 'w') as f:
        csv.writer(f).writerows([row] for row in list3)
    

    输出

    France
    Germany
    USA
    

    您可能根本不需要 CSV 模块。这也将写入列表。不同之处在于,如果您的数据中包含内部引号和逗号,那么第一个示例也会转义。

    import csv
    list3= ["France","Germany","USA"]
    with open('your_file.csv', 'w') as f:
        f.write("\n".join(list3))
    

    【讨论】:

      猜你喜欢
      • 2020-12-30
      • 1970-01-01
      • 2019-05-21
      • 2021-07-31
      • 2020-12-30
      • 2017-08-02
      • 2020-12-01
      • 2017-01-04
      • 1970-01-01
      相关资源
      最近更新 更多