python列表到csv会引发错误:可迭代,而不是numpy.int64 [英] Python list to csv throws error: iterable expected, not numpy.int64
问题描述
我想将列表写入csv,尝试执行此操作时会收到以下错误
I want to write a list into a csv,When trying to do it I receive the below error
out.writerows(fin_city_ids)
_csv.Error: iterable expected, not numpy.int64
我的代码如下
org_id.append([pol_id,bldest_id])
fin_ids=list(org_city_id['org_id'].unique())
print(fin_ids)
out = csv.writer(open("D:/dataset/fin_ids.csv","w"), delimiter='|')
out.writerows(fin_ids)
下面是fin_ids的输出
Below is the output from fin_ids
[1002774, 0, 1000702, 1000339, 1001620, 1000710, 1000202, 1003143, 147897, 31018, 1001502, 1002812, 1003026, 1003280, 1003289, 1002714, 133191, 5252218, 6007821, 1002632]
Org_id是一个包含重复ID的dataFrame.fin_ids是一个包含ID的不定值的列表.Fin ID是一个从数据帧org_id派生的唯一ID的列表.
Org_id is a dataFrame which contains duplicate ids .fin_ids is a list which contains unqiue values of ids .Fin ID is a list of unique ids derived from the data frame org_id.
所需的输出是CSV,所有值都放在单独的行中,因为稍后我将数据加载到sql表中.
output desired is a CSV with all the values in separate rows as I am going to load the data into a sql table later .
推荐答案
您可以通过多种方式完成此任务.但是,如果您希望从 csv
模块中进行 writerows
,则必须首先将列表 fin_ids
变成一系列列表:>
You can get this done in many ways. But if you wish to writerows
from the csv
module, then you will have to turn your list fin_ids
into a sequence of lists first:
fin_ids = [1002774, 0, 1000702, 1000339,
1001620, 1000710, 1000202, 1003143, 147897,
31018, 1001502, 1002812, 1003026, 1003280,
1003289, 1002714, 133191, 5252218, 6007821, 1002632]
outfile = open('D:/dataset/fin_ids.csv','w')
out = csv.writer(outfile)
out.writerows(map(lambda x: [x], fin_ids))
outfile.close()
另一种方法是只使用熊猫 Series
中的 .to_csv()
方法.由于您是从数据框开始的,因此您可以执行以下操作:
Another way would be to just use the .to_csv()
method from pandas Series
. Since you started with a dataframe, you could just do:
org_city_id['org_id'].unique().to_csv("D:/dataset/fin_ids.csv", index=False)
这两个都应生成包含以下数据的csv文件:
Both of these should generate a csv file with the following data:
1002774
0
1000702
1000339
1001620
1000710
1000202
1003143
147897
31018
1001502
1002812
1003026
1003280
1003289
1002714
133191
5252218
6007821
1002632
这篇关于python列表到csv会引发错误:可迭代,而不是numpy.int64的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!