Skip to main content
 首页 » 编程设计

python之Pandas Dataframe 一次追加一行到 CSV

2024年12月31日9lidabo

我正在尝试将 pandas 数据帧发送到 csv 文件中

import pandas as pd 
import os 
 
case_array = [['2017042724', '05/18/2017'], ['2017042723', '05/18/2017'], ['2017042722', '05/18/2017'], ['2017042721', '05/18/2017']] 
 
filename = 'case_array.csv' 
path = "C:\shares\folder" 
fullpath = os.path.join(path, filename) 
 
for case_row in case_array: 
    df = pd.DataFrame(case_row) 
    try: 
        with open(fullpath, 'w+') as f: 
            df.to_csv(f, header=False) 
            print('Success') 
    except: 
        print('Unable to Write CSV') 
 
try: 
    df = pd.read_csv(fullpath) 
    print(df) 
except: 
    print('Unable to Read CSV') 

但它会将每一行作为一列插入,插入一个标题列(设置为 False)并覆盖之前的插入:

0  2017042721 
1  05/18/2017 

如果我插入整个数组,它将插入没有标题行的行。 (这是我想要的正确结果)问题是我编写的脚本我需要一次插入每一行。

如何让 pandas dataframe 插入行而不是列?

编辑1

像这样:

 0            1 
 2017042721  05/18/2017 
 2017042723  05/18/2017 

请您参考如下方法:

您不必遍历数组即可执行此操作。您可以从数组中创建一个数据框,并使用 to_csv() 将其写入 csv。 .

case_array = [['2017042724', '05/18/2017'], ['2017042723', '05/18/2017'], ['2017042722', '05/18/2017'], ['2017042721', '05/18/2017']] 
 
df=pd.DataFrame(case_array) 
df.to_csv(fullpath, header=False) 

编辑

如果您必须遍历下面代码中的数组:

for case_row in case_array: 
    df = pd.DataFrame(case_row).T 
    try: 
        with open(fullpath, 'a') as f: 
            df.to_csv(f, header=False, index=False) 
            print('Success') 
    except: 
        print('Unable to Write CSV')