在python中创建csv文件

时间:2016-08-26 12:22:25

标签: python

我在python中创建了一个程序,其中我使用协同过滤来查找基于项目的CF.     我的代码是,

# Create a placeholder items for closes neighbours to an item
data_neighbours = pd.DataFrame(index=data_ibs.columns,columns=[range(1,13)])
print data_neighbours
# Loop through our similarity dataframe and fill in neighbouring item names
for i in range(0,len(data_ibs.columns)):
    ##use sort_values(...)
    data_neighbours.ix[i,:10] = data_ibs.ix[0:,i].sort_values(ascending=[1, 0])[:10].index
    data_neighbours.ix[i,:10] = data_ibs.ix[0:,i].sort_values(ascending=[1, 0])[:10].index



print data_neighbours.ix[i,:10]

Output is in table:


         user         1          2          3
    0   192.   c1s1b1p3   c1s1b1p4   c1s1b1p5
    1   192.   c1s1b1p3   c1s1b1p4   c1s1b1p5
    2   192.   c1s1b1p3   c1s1b1p4   c1s1b1p5
    3   192.   c1s1b1p3   c1s1b1p4   c1s1b1p5
    4   192.   c1s1b1p7   c1s1b1p8  c1s1b1p10
    5   192    c1s1b1p5   c1s1b1p6   c1s1b1p7
    6   192.   c1s1b1p3   c1s1b1p4   c1s1b1p5
    7   192.   c1s1b1p8   c1s1b1p9   c1s1b1p4
    8   192.   c1s1b1p6  c1s1b1p10   c1s1b1p5
    9   192.   c1s1b1p3   c1s1b1p5   c1s1b1p7
    10  192.   c1s1b1p6   c1s1b1p8   c1s1b1p9

这是在cmd提示符下的表格显示我想在csv文件中保存此表格。如何创建csv文件来存储此表。

2 个答案:

答案 0 :(得分:1)

with open('hi.csv','wb') as ff:
    sw=csv.writer(ff,delimiter=',',quoting=csv.QUOTE_MINIMAL) 
       for rows in data_neighbours: 
           sw.writerow(rows)

data_neighbours必须以行方式包含列表....

答案 1 :(得分:0)

您应该考虑使用csv module。在文档中,有创建csv文件所需的所有解释和示例。