我使用哪个变量将数据写入csv文件

zfycwa2u  于 12个月前  发布在  其他
关注(0)|答案(2)|浏览(93)

我该如何调整我的代码,以便我可以打印借方和贷方到csv文件。
我已经包含了下面的代码,但在使用csv模块时,我很难理解要使用哪些变量以及在哪里使用。我还包括了当前得到的错误消息和打印到屏幕上的数据示例。我想写入文件的就是这些数据。

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sun Jul  2 16:23:17 2023

@author: admin
"""

import pandas as pd
import numpy as np
import csv

# read a csv file
bs = pd.read_csv('mar_2022_bs.csv', index_col=False)
pd.options.display.max_rows = 350

# clean the data removing empty fields and replacing with appropriate data if
# necessary
bs["Debit Amount"].fillna(0.0, inplace = True)
bs["Credit Amount"].fillna(0.0, inplace = True)
bs["Transaction Type"].fillna('OSC', inplace = True)

# Filter the debits by taking out the transactions types, descriptions and
# codes that are not required
debit_amount = bs[(bs['Debit Amount'] > 0) & 
    (bs['Transaction Description'] != 'M HART') & 
    (bs['Transaction Type'] != 'TFR') & 
    (bs['Transaction Description'] != 'ADELE WEEKLY') & 
    (bs['Transaction Description'] != 'SAVE THE CHANGE') & 
    (bs['Transaction Description'] != 'MANSELTON STORES') & 
    (bs['Transaction Description'] != 'Netflix.com')]

print(debit_amount[['Transaction Type', 'Transaction Description', 'Debit Amount']])

print('\nTotal for Month: ', debit_amount['Debit Amount'].aggregate(np.sum), '\n')

# Filter the credits by taking out the transactions types, descriptions and
# codes that are not required
credit_amount = bs[(bs['Credit Amount'] > 0) & 
    (bs['Transaction Description'] != 'CLUB LLOYDS WAIVED') & 
    (bs['Transaction Type'] != 'TFR') & 
    (bs['Transaction Type'] != 'BGC')]

print(credit_amount[['Transaction Type','Transaction Description', 'Credit Amount']])

print('\nTotal for Month: ', credit_amount['Credit Amount'].aggregate(np.sum), '\n')

# writing the debit and credit lists to  a csv file

csvfile = 'money_out.csv'
with open(csvfile, 'w', newline='') as debit_amount:
    writer = csv.writer(debit_amount)
    writer.writerow(debit_amount)
    writer.writerows(debit_amount)

错误消息:

Traceback (most recent call last):

  File ~/anaconda3/lib/python3.10/site-packages/spyder_kernels/py3compat.py:356 in compat_exec
    exec(code, globals, locals)

  File ~/my_acc_v1.py:55
    writer.writerow(debit_amount)

UnsupportedOperation: not readable

屏幕输出示例:

Transaction Type Transaction Description  Credit Amount
2                DEP           MOBILE CHEQUE          20.00
6                FPI            COONEY JAMES          22.00
7                FPI                   GC C1          16.56
x759pob2

x759pob21#

with open(csvfile, 'w', newline='') as debit_amount: # <- you are overwriting the DataFrame from further above, you should avoid that
    writer = csv.writer(debit_amount)  
    writer.writerow(debit_amount) # <-- the error occures, because with debit_amount you are passing a fileobject to writerow(); what you probably want to pass is credit_amount
    writer.writerows(debit_amount) # <-- the same error

顺便说一下,除了使用csv模块,你还可以使用pandas内置的导出功能:

credit_amount.to_csv(csvfile)
zi8p0yeb

zi8p0yeb2#

如果要使用csv模块来写入csv文件,则必须将 rows 传递给writerow方法。
原始的方法(没有索引,没有列)是使用dataframe的value,它给出了一个可迭代的行:

csvfile = 'money_out.csv'
with open(csvfile, 'w', newline='') as debit_amount:
    csvfile.writerows(credit_amount.values())

但是,由于您已经有了一个Pandas Dataframe ,使用to_csv可能更简单,如@Flow的回答所示

相关问题