【问题标题】:Python: Creating Multiple Text file from a column in CSV filePython:从 CSV 文件中的列创建多个文本文件
【发布时间】:2021-09-17 19:38:29
【问题描述】:

我有一个 CSV 文件,其中包含 3 列 Imagename 、 image_size 和 class。我想创建多个读取 CSV 的文本文件,其中 Imagename 作为文件名,image_size 和 class 作为文件内容。

我需要遍历 Imagename,如果 Imagename 相似,则将相应的 image_size 和 class 添加到单个 txt 文件中。

如果 Imagename 不同,则创建另一个 txt 文件并附加其对应的 image_size、类。

以下是示例 csv:

Image_name   image_size  class
Img_0001     150         brightness 
Img_0001     153         Noise
Img_0001     170         skewness
Img_0002     132         brightness
Img_0002     188         Noise
Img_0002     191         skewness
Img_0003     159         brightness
Img_0003     111         Noise
Img_0003     170         skewness

我需要创建的文件名:

Img_0001.txt 

以及txt文件中的文件内容:

150         brightness 
153         Noise
170         skewnes

【问题讨论】:

    标签: python pandas list csv text


    【解决方案1】:

    使用pd.read_csv 读取您的CSV 文件后,您可以通过以下方式为每个唯一的Image_name 条目创建txt 文件。

    for image in df.Image_name.unique():
        fileName = image +".txt"
        file = open(fileName,"w+") #creating a txt file if not already exists
        
        #adding rows for each unique image name 
        for row in df[df.Image_name==image].values:
            file.write(f"{row[1]} {row[2]}") #writing to txt file
    

    这里df.Image_name.unique() 返回Image_name 列下的所有唯一值。然后我们为每个名称运行循环并从 CSV 中检索信息并将这些信息添加到 txt 文件中。

    【讨论】:

      【解决方案2】:

      您可以使用pd.read_csv 读取CSV 文件,然后根据Image_name 使用.groupby() 将数据帧“拆分”到多个数据帧。例如:

      df = pd.read_csv("your_file.csv")
      
      for filename, g in df.groupby("Image_name"):
          g.to_csv(filename + ".txt", index=False)
      

      创建Img_000*.txt 文件。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-28
        • 2019-03-24
        • 2011-02-06
        • 2016-10-15
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多