Pandas创建一个空DataFrame,并逐行插入数据,并保存

创建一个空的Dataframe
result =pd.DataFrame(columns=('idx','degree','weight','diameter'))
#将计算结果逐行插入result,注意变量要用[]括起来,同时ignore_index=True,否则会报错,ValueError: If using all scalar values, you must pass an index
for i in idx:
    degree=
    weight=
    diameter=
    result=result.append(pd.DataFrame({'idx':[i],'degree':[degree],'weight':[weight],'diameter':[diameter]}),ignore_index=True)

将创建的数据写入到成csv文件中,

result.to_csv(‘filename.csv’,, sep="," ,index=False )

另一种方法用csv包,一行一行写入

可参考:https://blog.csdn.net/waple_0820/article/details/70049953

import csv

#python2可以用file替代open
with open("test.csv","w") as csvfile: 
    writer = csv.writer(csvfile)

    #先写入columns_name
    writer.writerow(["index","a_name","b_name"])
    #写入多行用writerows
    writer.writerows([[0,1,3],[1,2,3],[2,3,4]])
index   a_name  b_name
0       1       3
1       2       3
2       3       4

你可能感兴趣的:(pandas,编程基础)