Python list to csv 抛出错误:iterable expected,not numpy.int64
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39282516/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python list to csv throws error: iterable expected, not numpy.int64
提问by arpit joshi
I want to write a list into a csv,When trying to do it I receive the below error
我想将列表写入 csv,尝试执行此操作时收到以下错误
out.writerows(fin_city_ids)
_csv.Error: iterable expected, not numpy.int64
My code is as below
我的代码如下
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)
Below is the output from fin_ids
下面是 fin_ids 的输出
[1002774, 0, 1000702, 1000339, 1001620, 1000710, 1000202, 1003143, 147897, 31018, 1001502, 1002812, 1003026, 1003280, 1003289, 1002714, 133191, 5252218, 6007821, 1002632]
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.
Org_id 是一个包含重复 ids 的数据帧。fin_ids 是一个包含 ids 唯一值的列表。Fin ID 是从数据帧 org_id 派生的唯一 id 列表。
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 文件,所有值都在单独的行中,因为我稍后会将数据加载到 sql 表中。
回答by Abdou
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:
您可以通过多种方式完成这项工作。但是如果你想writerows
从csv
模块中,那么你必须fin_ids
先把你的列表变成一个列表序列:
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()
Another way would be to just use the .to_csv()
method from pandas Series
. Since you started with a dataframe, you could just do:
另一种方法是只使用.to_csv()
pandas的方法Series
。由于您从数据框开始,您可以这样做:
org_city_id['org_id'].unique().to_csv("D:/dataset/fin_ids.csv", index=False)
Both of these should generate a csv file with the following data:
这两个都应该生成一个包含以下数据的 csv 文件:
1002774
0
1000702
1000339
1001620
1000710
1000202
1003143
147897
31018
1001502
1002812
1003026
1003280
1003289
1002714
133191
5252218
6007821
1002632