Python-csv文件打开、csv文件保存和csv文件删除行信息

以行人重识别的数据集Market1501为例,对数据集图片的18个关节点坐标文件  pckh_train.csv 进行:

csv文件打开csv文件保存csv文件删除行信息操作。

 

首先展示  pckh_train.csv  文件:

Python-csv文件打开、csv文件保存和csv文件删除行信息_第1张图片

接着摆出代码, 即csv文件打开csv文件保存csv文件删除行信息操作:

import csv

# 如果 pckh_train=>relabel=True  
# 如果 pckh_test=>relabel=False
# 如果 pckh_query=>relabel=False
relabel=True
path = './pckh_train.csv'
list_n = []

############## 删除是-1的列表元素################
def del_neg(list):
    while -1 in list:
        for i in list:
            if i == -1:
                list.remove(i)
            else:
                continue
    return list

############ 转换成 pids, camid,sid, kid查找##################
with open(path, 'r', encoding="utf-8") as myFile:
    raws = csv.reader(myFile)
    # print(raws)
    for raw in raws:
        list_n.append(raw)

    # id 转换
    pid_container = set()
    for i in range(1, len(list_n)):
        l = list_n[i][0].split('_')
        # print(l) #['0002', 'c1s1', '000451', '03.jpg']
        pids = int(l[0])
        if pids == -1: continue  # junk images are just ignored
        pid_container.add(pids)
    pid2label = {pid: label for label, pid in enumerate(pid_container)}
    # print(pid2label)

   ################### id + camid + sid + kid + qid==> 保存为新的csv文件###############################
    for i in range(1, len(list_n)):
        l = list_n[i][0].split('_')
        # print(l) ['0002', 'c1s1', '000451', '03.jpg']
        pids, camid, sid, kid, qid = int(l[0]), int(l[1][1]), int(l[1][3]), int(l[2]),int((l[3][:-4]))

        if pids == -1: continue
        assert 0 <= pids <= 1501  # pid == 0 means background
        assert 1 <= camid <= 6
        camid -= 1  # index starts from 0
        if relabel:pid = pid2label[pids]
        # list_name = int(pids + camid + sid + kid + qid)
        list_name = [pids,camid,sid,kid,qid]
        # print(list_name)# [76, 6, 1, 19051]
        # # pids, camid, sid, kid
        # print('pids',pids)
        # print('camid',camid)
        # print('sid',sid)
        # print('kid',kid)

        y = list_n[i][1]
        x = list_n[i][2]
        row = [list_name, y, x]
        out = open(path, "a", newline="")
        csv_writer = csv.writer(out, dialect="excel")
        csv_writer.writerow(row)

############# 删除csv文件行数#######################
import pandas as pd
csv_data = pd.read_csv('pckh_train.csv',header=None)
csv_data1=csv_data.drop(range(1,len(list_n)),axis=0,inplace=True)
csv_data.to_csv('pckh_train_1.csv',index=False,sep=',',header=None)

 最后展示最终删除行之后保存为 pckh_train_1.csv  文件的效果图:

Python-csv文件打开、csv文件保存和csv文件删除行信息_第2张图片

 

你可能感兴趣的:(python,Python,csv文件打开,csv文件保存,csv文件删除行)