im in noobie in python。我想从熊猫的csv中获取一些数据,并在写入新的csv文件后,并以格式添加额外的数据 “类型”;“货币”;“金额”;“注释” “ type1”;“ currency1”;“ amount1”;“ comment1” 等等
import pandas as pd
import csv
req=pd.read_csv('/Users/user/web/python/Bookcopy.csv')
type="type"
comment = "2week"
i=0
while i<3:
Currency = req['Currency'].values[i]
ReqAmount = req['Request'].values[i]
r = round(ReqAmount,-1)
i+=1
data =[type,Currency,r,comment]
#print(data)
csv_file = open('data2.csv', 'w')
with csv_file:
writer = csv.writer(csv_file)
writer.writerow(data)
print("DONE")
writer.writerows(数据) _csv.Error:可迭代,不是numpy.float64
答案 0 :(得分:0)
我有很多事情要批评。我希望它不会带来卑鄙,而是具有教育意义。尽管您的代码不管这些要点都可以工作,但是遵循它们是一种很好的编码风格。
Currency
和ReqAmount
应该是currency
和reqAmount
。type
是python关键字。也就是说,让我尝试遍历您的代码并为您提供提示和技巧:
main()
方法。只是更好的编码风格。i=0; while i<3; i+=1
构造,而应使用for i in range(3)
。虽然有效,但它不是pythonic,很难阅读。len(req)
从csv文件中读取行数。data =[type,Currency,r,comment]
不断覆盖您的data
变量。您可以附加到data
,然后将所有内容最后写入输出文件,或者在每次迭代中直接写入输出文件。open
创建变量(除非绝对必要)。而是在open
语句中使用with
。这样可以确保文件正确关闭。我已经看到您确实使用过with
语句,不过您通常会像with open(...) as variable_name:
那样使用它。pandas
进行csv读取,请同时使用它进行写入。如果您使用csv
库进行书写,也可以使用它进行阅读。虽然混合它们不是错误,但这是不好的样式,并且会创建比所需更多的依赖项。我不太了解您的代码应该做什么,所以我只是猜测并希望它朝着正确的方向发展。
固定所有这些点时,您可能会遇到类似的事情:
import pandas as pd
import csv
def main():
req=pd.read_csv('/Users/user/web/python/Bookcopy.csv')
transferType = "type"
comment = "2week"
with open('data2.csv', 'w') as csv_file:
writer = csv.writer(csv_file)
writer.writerow(["type","currency","amount","comment"])
for i in range(len(req)):
currency = req['Currency'].values[i]
reqAmount = req['Request'].values[i]
r = round(reqAmount,-1)
data = [transferType,currency,r,comment]
#print(data)
writer.writerow(data)
print("DONE")
# Whenever you run a program, __name__ will be set to '__main__' in the initial
# script. This makes it easier later when you work with multiple code files.
if __name__ == '__main__':
main()