代码之家  ›  专栏  ›  技术社区  ›  Rio

如何使用python过滤CSV文件中两个日期之间的行并重定向到另一个文件?

  •  1
  • Rio  · 技术社区  · 6 年前

    我是Python的新手。我有一个CSV文件下面的数据作为一个例子。我想跳过特定日期范围(2018-08-01到2018-08-28)之间的行,并将输出重定向到单独的CSV文件。请注意,标题“上次使用”中有空格。

    NUMBER,MAIL,COMMENT,COUNT,LAST USE,PERCENTAGE,TEXTN
    343,user1@example.com,"My comment","21577",2018-08-06,80.436%,
    222,user2@example.com,"My comment","31181",2018-07-20,11.858%,
    103,user3@example.com,"My comment",540,2018-06-14,2.013%,
    341,user4@example.com,"My comment",0,N/A,0.000%,
    

    2 回复  |  直到 6 年前
        1
  •  2
  •   jpp    6 年前

    对于熊猫来说,这很简单:

    import pandas as pd
    
    # read file
    df = pd.read_csv('file.csv')
    
    # convert to datetime
    df['LAST USE'] = pd.to_datetime(df['LAST USE'])
    
    # calculate mask
    mask = df['LAST USE'].between('2018-08-01', '2018-08-28')
    
    # output masked dataframes
    df[~mask].to_csv('out1.csv', index=False)
    df[mask].to_csv('out2.csv', index=False)
    

    也可以组合布尔数组来构造 mask

    m1 = df['LAST USE'] >= (pd.to_datetime('now') - pd.DateOffset(days=30))
    m2 = df['LAST USE'] <= pd.to_datetime('now')
    mask = m1 & m2
    
        2
  •  0
  •   vicente louvet    6 年前

    dict阅读器文档: https://docs.python.org/3/library/csv.html#csv.DictReader

    strtime文档: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

    对于每一行,我们将日期/时间字符串转换为实际的日期/时间对象,然后python可以将其与日期范围进行比较。如果值在范围内,我们将把整行写入一个单独的CSV文件。

    import datetime, csv
    
    #define all the fieldnames in the input CSV file (for use in creating / appending to output CSV file)
    fieldnames = ['NUMBER','MAIL','COMMENT','COUNT','LAST USE','PERCENTAGE','TEXTN']
    
    #open input CSV file as readonly
    with open("input.csv", "r") as fin:
        #create a CSV dictionary reader object
        csv_dreader = csv.DictReader(fin)
        #iterate over all rows in CSV dict reader
        for row in csv_dreader:
            #check for invalid Date values
            if 'N/A' not in row['LAST USE']:
                #convert date string to a date object
                datetime_val = datetime.datetime.strptime(row['LAST USE'], '%Y-%m-%d')
                #check if date falls within requested range
                if datetime_val > datetime.datetime(2018, 8, 1) and datetime_val < datetime.datetime(2018, 8, 28):                
                    #if it does, open output CSV file for appending
                    with open("output.csv", "a") as fout:
                        #create a csv writer object using the fieldnames defined above
                        csv_writer = csv.DictWriter(fout, fieldnames=fieldnames)
                        #write the current row (from the input CSV) to the output CSV file
                        csv_writer.writerow(row)