提问人:n3cr05c0p3 提问时间:8/22/2023 最后编辑:quamranan3cr05c0p3 更新时间:8/22/2023 访问量:57
我使用哪个变量将数据写入 csv 文件
which variable do I use to write the data to csv file
问:
我将如何调整我的代码,以便我可以将借方和贷方打印到 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
答:
1赞
Flow
8/22/2023
#1
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)
0赞
Serge Ballesta
8/22/2023
#2
如果要使用该模块写入 csv 文件,则必须将行传递给该方法。csv
writerow
做到这一点的原始方法(没有索引,没有列)是使用 的 数据帧,它给出了行的可迭代性:value
csvfile = 'money_out.csv'
with open(csvfile, 'w', newline='') as debit_amount:
csvfile.writerows(credit_amount.values())
但是,由于您已经拥有 Pandas 数据帧,因此使用起来可能更简单,如 @Flow 的回答所示to_csv
评论