【问题标题】:Python csv: find the latest record with a conditionPython csv:查找具有条件的最新记录
【发布时间】:2020-11-30 10:35:22
【问题描述】:

我有一个包含以下示例数据的 csv:

id bb_id cc_id datetime
-------------------------
1  11    44    2019-06-09
2  33    55    2020-06-09
3  22    66    2020-06-09
4  11    44    2019-06-09
5  11    44    2020-02-22

假设条件是if bb_id == 11 and cc_id == 44获取最新记录,即:

11    44    2020-02-22

如何从 csv 中获取此信息?

我做了什么:

 with open('sample.csv') as csv_file
     for indx, data in enumerate(csv.DictReader(csv_file)):
         # check if the conditional data is in the file?
         if data['bb_id'] == 11 and data['cc_id'] == 44:
                     # sort the data by date? or should I store all the relevant data before hand in a data structure like list and then apply sort on it? could I avoid that? as I need to perform this interactively multiple times

【问题讨论】:

  • 你会考虑使用熊猫吗?
  • 这不能使用 csv 模块吗?
  • 当然可以。熊猫只是让它变得微不足道。
  • 当然,我认为最好先检查 bbcc 值是否存在于 csv 中,如果它们仅查找最新记录?

标签: python python-3.x csv sorting


【解决方案1】:

如果你真的想在普通的 python 中做这件事,这样的事情很简单:

with open('sample.csv') as csv_file:
    list_of_dates = []
    for indx, data in enumerate(csv.DictReader(csv_file)):
         if data['bb_id'] == 11 and data['cc_id'] == 44:
             list_of_dates.append(data['datetime'])

   sorted = list_of_dates.sort()
   print( sorted[-1] ) # you already know the values for bb and cc

也试试:

def sort_func(e):
    return e['datetime']

with open('sample.csv') as csv_file:
    list_of_dates = []
    for indx, data in enumerate(csv.DictReader(csv_file)):
         if data['bb_id'] == 11 and data['cc_id'] == 44:
             list_of_dates.append(data)

    sorted = list_of_dates.sort(key=sort_func)
    print( sorted[-1] )

【讨论】:

  • 他们想要完整的记录,而不仅仅是日期。
【解决方案2】:

将所有选中的记录放在一个列表中,然后使用max()函数,以日期为key。

selected_rows = []
with open('sample.csv') as csv_file
    for data in csv.DictReader(csv_file):
        # check if the conditional data is in the file?
        if data['bb_id'] == 11 and data['cc_id'] == 44:
            selected_rows.append(data)
latest = max(selected_rows, key = lambda x: x['datetime'])
print(latest)

【讨论】:

    【解决方案3】:

    我知道的最简单的方法:

    import pandas as pd
    import pandasql as ps
    
    sample_df = pd.read_csv(<filepath>);
    
    ps.sqldf("""select *
                from (select * 
                from sample_df
                where bb_id = 11 
                 and cc_id = 44
                 order by datetime desc) limit 1""", locals())
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-22
      • 2021-11-03
      • 2012-07-31
      • 1970-01-01
      相关资源
      最近更新 更多