程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python operates csv to modify the content and save it

編輯:Python

目的:修改csvThe format and content of a column of data,Finally save the outputcsv

python實現代碼如下

import csv
import datetime
import pandas as pd
if __name__ == '__main__':
## 文件路徑
csv_path = './data/ganglia-metrics.csv'
## Export file naming
new_csv_name = "new_ganglia-metrics.csv"
## 讀取csv信息
data = pd.read_csv(csv_path)
## I only have two columns of data,Two arrays are defined,After processing, store it in the array,Finally save the output
timestampList = []
cpu_idleList = []
# 修改csvA column of data information
for i in range(data.shape[0]):
# 修改格式
t = (datetime.datetime.strptime(data.loc[i]['Timestamp'], "%Y-%m-%dT%H:%M:%S+00:00") + datetime.timedelta(
hours=2)).strftime("%Y-%m-%d %H-%M-%S")
# 寫入數組
timestampList.append(t)
cpu_idleList.append(data['cpuIdle'][i])
# 寫出到csv
with open(new_csv_name, "w", newline="") as csvfile:
writer = csv.writer(csvfile)
# 先寫入columns_name
writer.writerow(["Timestamp", "cpuIdle"])
for i in range(len(timestampList)):
writer.writerow([timestampList[i], cpu_idleList[i]])

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved