我该如何调整我的代码,以便我可以打印借方和贷方到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
2条答案
按热度按时间x759pob21#
顺便说一下,除了使用csv模块,你还可以使用pandas内置的导出功能:
zi8p0yeb2#
如果要使用
csv
模块来写入csv文件,则必须将 rows 传递给writerow
方法。原始的方法(没有索引,没有列)是使用dataframe的
value
,它给出了一个可迭代的行:但是,由于您已经有了一个Pandas Dataframe ,使用
to_csv
可能更简单,如@Flow的回答所示