python对csv文件追加写入列的方法
时间:2023-01-22 11:44:54|栏目:Python代码|点击: 次
python对csv文件追加写入列,具体内容如下所示:
原始数据
[外链图片转存失败(img-zQSQWAyQ-1563597916666)(C:\Users\innduce\AppData\Roaming\Typora\typora-user-images\1557663419920.png)] import pandas as pd import numpy as np data = pd.read_csv(r'平均值.csv') print(data.columns)#获取列索引值 data1 = data['flow']#获取列名为flow的数据作为新列的数据 data['cha'] = data1 #将新列的名字设置为cha data.to_csv(r"平均值12.csv",mode = 'a',index =False) #mode=a,以追加模式写入,header表示列名,默认为true,index表示行名,默认为true,再次写入不需要行名 print(data)
结果:
[外链图片转存失败(img-aZrOOdBp-1563597916667)(C:\Users\innduce\AppData\Roaming\Typora\typora-user-images\1557663438561.png)]
知识点扩展:
python:在csv文件每行末写入一列――方法1
with open(os.path.join(os.path.dirname(__file__), "file1")) as csvFile: rows = csv.reader(csvFile) with open(os.path.join(os.path.dirname(__file__), "file2"), 'w') as f: writer = csv.writer(f) for row in rows: row.append(“123465”) writer.writerow(row)
总结