目的:修改csv某列数据格式及内容,最后再保存输出csv

python实现代码如下

import csv
import datetime
import pandas as pd

if __name__ == '__main__':
	## 文件路径
    csv_path = './data/ganglia-metrics.csv'
    ## 导出文件命名
    new_csv_name = "new_ganglia-metrics.csv"
    ## 读取csv信息
    data = pd.read_csv(csv_path)
    ## 我就只有两列数据,就定义了两个数组,处理完存放再数组里,最后再保存输出
    timestampList = []
    cpu_idleList = []
    
    # 修改csv某列数据信息
    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]])

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐