如何编辑CSV文件列并对其运行for循环

2024-10-06 10:31:35 发布

您现在位置:Python中文网/ 问答频道 /正文

嗨,我有一个CSV文件,有1200行和3列

Pat_ID | System_Disc | Syndrom_Disk
U-P-009  Respiratory    Pneumonia
U-P-010  Skin           Abscess

我想在Pat_Id列中运行一个for循环来删除破折号(-),这样Pat_Id就变成了UP009而不是U-p-009。我该怎么做


Tags: 文件csvidforsystemskindiscdisk
1条回答
网友
1楼 · 发布于 2024-10-06 10:31:35

使用熊猫

  • 使用^{}创建数据帧。如果有除,之外的分隔符,请使用sep参数
    • 现在,数据的格式也非常好,可以进行进一步的分析和可视化
  • 使用^{}
  • 使用^{}将其保存回csv
import pandas as pd

# create the dataframe
df = pd.read_csv('file.csv')

# display(df)
    Pat_ID  System_Disc Syndrom_Disk
0  U-P-009  Respiratory    Pneumonia
1  U-P-010         Skin      Abscess

# clean the Pat_ID column
df.Pat_ID = df.Pat_ID.str.replace('-', '')

# display(df) after fixing column
  Pat_ID  System_Disc Syndrom_Disk
0  UP009  Respiratory    Pneumonia
1  UP010         Skin      Abscess

使用CSV

import csv

with open('test.csv', 'r+', newline='') as f:  # open file
    lines = list(csv.reader(f, delimiter='|'))  # reads file in as a list of lists
    for i, line in enumerate(lines):
        if i > 0:  # skips the header
            lines[i][0] = line[0].replace('-', '')  # replaces the -
    f.seek(0)  # locates the beginning of the file
    f.truncate()  # removes previous contents
    writer = csv.writer(f)
    writer.writerows(lines)  # write back to csv file


# resulting file
Pat_ID,System_Disc,Syndrom_Disk
UP009,Respiratory,Pneumonia
UP010,Skin,Abscess

相关问题 更多 >