简体   繁体   English

Python - 从 csv 读取数据,然后使用循环中的数据和文件号写入新的 csv

[英]Python - Reading in data from csv and then writing to new csv with data and file number from loop

My objective is to:我的目标是:

  • Read in all of the files from the directory which start with letter "Z".从目录中读取以字母“Z”开头的所有文件。
  • Read in the Temperature column from each.csv in the directory.从目录中的 each.csv 中读取温度列。
  • Open a new.开一个新的。 csv : csv
    • Add the Temperature column to the new.将温度列添加到新的。 csv . csv
    • Add a column, "File #" to this new .csv , and iterate 1,2,3,4 based on the number of files that I read in through the loop.在这个新的.csv中添加一列“File #”,并根据我通过循环读取的文件数迭代 1、2、3、4。
  • I'm currently stuck with how to:我目前坚持如何:
    • Create the.csv file and open it in every loop.创建 .csv 文件并在每个循环中打开它。
    • Add the Temperature Column and the File # column (with File # incremented) into the.csv file.将温度列和文件 # 列(文件 # 递增)添加到 .csv 文件中。

import pandas as pd import csv from glob import glob从全局导入 pandas 作为 pd 导入 csv 从全局导入全局
filenames = glob("C:/Users/Z*.csv")文件名 = glob("C:/Users/Z*.csv")

for f in filenames:
    df = pd.read_csv(f, sep=',',skiprows=24)
    df.columns=['sample','Time','ms','Temperature']
    df=df.astype(str)
    df["Temperature"] = df["Temperature"].str.replace('\+ ', '').str.replace(' ', '').astype(float)
    
    # I need to add the column, "File #" to the Dataframe

    df.to_csv('my_csv.csv', mode='a', columns=[['Temperature','File #']] header=False)
    # Is df.to_csv is the best option here?
    
    # Then, I need to iterate the file # for the next loop.

在此处输入图像描述

please find my suggestions below - hope this helps!请在下面找到我的建议-希望这会有所帮助!

for i, f in enumerate(filenames):
    df = pd.read_csv(f, sep=',',skiprows=24)
    df.columns=['sample','Time','ms','Temperature']
    df=df.astype(str)
    df["Temperature"] = df["Temperature"].str.replace('\+ ', '').str.replace(' ', '').astype(float)
    
    # I need to add the column, "File #" to the Dataframe
    df['File #'] = i
    
    df.to_csv('my_csv.csv', mode='a', columns=[['Temperature','File #']] header=False)
    # Is df.to_csv is the best option here? - probably yes
    

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM