【问题标题】:Find a duplicate row with max data查找具有最大数据的重复行
【发布时间】:2018-02-07 15:07:13
【问题描述】:

我有一个这样的 csv 文件:

Date of event       Name        Date of birth
06.01.1986          John Smit   23.08.1996
18.12.1996          Barbara D   01.08.1965
12.12.2001          Barbara D   01.08.1965
17.10.1994          John Snow   20.07.1965

我必须通过“姓名”和“出生日期”(可能与其他一些列)但具有 MAX 日期来查找唯一行。

所以我必须像这样获取 csv 文件:

Date of event       Name        Date of birth
06.01.1986          John Smit   23.08.1996
12.12.2001          Barbara D   01.08.1965
17.10.1994          John Snow   20.07.1965

如何做到这一点?我没有任何想法..

【问题讨论】:

  • find unique rowsfind a duplicate row?
  • 找到唯一的行,而且我需要将此解决方案与源列结合起来......并且还要写入 csv
  • 与源结合是什么意思?唯一的来自源,如果与非唯一的结合,结果被污染了。
  • Pandas 将数据帧写入 CSV 文件,stackoverflow.com/q/16923281/1278112

标签: python csv sorting max


【解决方案1】:

格式化

由于你的列名有空格,最好用逗号分隔。

算法

您可以使用 pandas 库来执行此操作:

import tempfile
import pandas

# create a temporary csv file with your data (comma delimited)
temp_file_name = None
with tempfile.NamedTemporaryFile('w', delete=False) as f:
    f.write("""Date of event,Name,Date of birth
06.01.1986,John Smit,23.08.1996
18.12.1996,Barbara D,01.08.1965
12.12.2001,Barbara D,01.08.1965
17.10.1994,John Snow,20.07.1965""")
    temp_file_name = f.name

# read the csv data using the pandas library, specify columns with dates
data_frame = pandas.read_csv(
    temp_file_name,
    parse_dates=[0,2],
    dayfirst=True,
    delimiter=','
)

# use groupby and max to do the magic
unique_rows = data_frame.groupby(['Name','Date of birth']).max()

# write the results
result_csv_file_name = None
with tempfile.NamedTemporaryFile('w', delete=False) as f:
    result_csv_file_name = f.name
    unique_rows.to_csv(f)

# read and show the results
with open(result_csv_file_name, 'r') as f:
    print(f.read())

这会导致:

Name,Date of birth,Date of event
Barbara D,1965-08-01,2001-12-12
John Smit,1996-08-23,1986-01-06
John Snow,1965-07-20,1994-10-17

【讨论】:

  • 但是如果我想写这个结果,我该怎么办?我需要按最大日期分组的 csv 以及源 csv 的所有列。
  • @AlexandrLebedev 我更新了我的答案,也写出了 csv。你真的应该只使用谷歌来查找一些文档。 pandas.pydata.org/pandas-docs/stable/generated/…
【解决方案2】:
import pandas as pd

# read the csv in with pandas module

df = pd.read_csv('pathToCsv.csv', header=0, parse_dates=[0, 2])

# set the column names as more programming friendly  i.e. no whitespace

df.columns = ['dateOfEvent','name','DOB'] # and probably some other columns ..

# keep row only with max (Date of event) per group ( name, Date of Birth )

yourwish = =df.groupby(['Name','DOB'])['dateOfEvent'].max()

【讨论】:

  • 非常感谢,它可以帮助我找到这些行,但我还需要将结果与源 csv-columns 结合起来
  • 这是什么意思
猜你喜欢
  • 1970-01-01
  • 2015-07-11
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-19
  • 2020-08-24
  • 2019-08-05
相关资源
最近更新 更多