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

标签 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 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')

关于python - Pandas Dataframe 一次追加一行到 CSV,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50415407/

相关文章:

python - 如何为py.test设置动态默认参数?

python - 按子字符串条件过滤 pandas DataFrame

python - 如何对多索引数据帧进行上采样以确保每个分组涵盖相同的时间范围(提供自定义开始和结束日期时间)

python - Pandas read_csv : Data is not being read from text file (open() reads hex chars)

r - 在R中将data.frames写入csv时如何命名多个csv文件?

python - 从python中为postgresql中的union中的每个查询选择特定列

Python requests 模块 - 将嵌套 XML 作为查询参数传递

python - tkinter 中的新窗口标题

python - 用数据框中列表中的值替换索引

python - 将数据框中相同的列值分组,并将相同值的总和添加为新列