Pandas Dataframe一次将一行追加到CSV

时间:2018-05-18 16:11:09

标签: python pandas dataframe export-to-csv

我正在尝试将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数据框插入行而不是列?

EDIT1

像这样:

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

1 个答案:

答案 0 :(得分:0)

您不必遍历数组来执行此操作。您可以从数组中创建一个数据帧,并使用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')