熊猫如何将列表保存到CSV

时间:2020-06-18 22:27:45

标签: python pandas jupyter

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

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

但是输出是水平的而不是垂直的,如果有人知道如何消除输出中的引号,我也将不胜感激。

输出上面的代码:enter image description here

我想要的输出: enter image description here

2 个答案:

答案 0 :(得分:2)

这是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

或使用print file参数:

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')一起使用。

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

答案 1 :(得分:1)

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

France
Germany
USA

输出

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

您可能根本不需要CSV模块。这也将写入列表。区别在于,如果您的数据中有问题,则第一个示例还将转义内部引号和逗号。

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>
int myglobal=0;
void *thread_function(void *arg){
    int i, j;
    for(i=0;i<20;i++){
        j=myglobal;
        j=j+1;
        printf(".");
        fflush(stdout);
        sleep(1);
        myglobal=j;
        }
        return NULL;
    }
    int main(void){
        pthread_t mythread;
        int i;
        if(pthread_create(&mythread, NULL, thread_function, NULL)){
            fprintf(stderr, "Error, pthread_create\n");
            exit(EXIT_FAILURE);
        }
        for(i=0;i<20;i++){
            myglobal=myglobal+1;
            printf("o");
            fflush(stdout);
            sleep(1);
        }
        if(pthread_join(mythread, NULL)){
            fprintf(stderr, "Error, pthread_join.");
            exit(EXIT_FAILURE);
        }
        printf("\nmyglobal = %d\n", myglobal);
        exit(0);
    }