[英]Pandas - min of a column for each value in other
I have a CSV file as follows: 我有一个CSV文件,如下所示:
Date, Name
2015-01-01 16:30:00.0, John
2015-02-11 16:30:00.0, Doe
2015-03-01 16:30:00.0, Sam
2015-03-05 16:30:00.0, Sam
2015-04-21 16:30:00.0, Chris
2015-05-07 16:30:00.0, John
2015-06-08 16:30:00.0, Doe
You can see that same name is repeated on multiple date. 您会看到同一名称在多个日期重复出现。 I want to know for each unique name, what is the MAX date in date column.
我想知道每个唯一名称的日期列中的最大日期是多少。 How to do this with Pandas or other solution if you know any in Python?
如果您对Python有所了解,如何使用Pandas或其他解决方案来做到这一点?
I want the result like: 我想要这样的结果:
Name, Max date(or latest)
John, 2015-01-01 16:30:00.0
Doe, 2015-01-01 16:30:00.0
Sam, 2015-01-01 16:30:00.0
Chris, 2015-01-01 16:30:00.0
You want to do DataFrame.groupby()
and then on it call - .max()
/ .min()
(Depending on what you want) . 你想干什么
DataFrame.groupby()
然后就可以调用- .max()
/ .min()
取决于你想要什么)。 Example - 范例-
df.groupby('Name').max()
You would also need to make sure that when you read in the csv, you parse the 'Date'
column as datetime, by using the dtype
argument for .read_csv()
method (as given below in the example). 您还需要确保当你在阅读的CSV,您解析
'Date'
列日期时间,使用dtype
的参数.read_csv()
方法(如在下面的例子中给出)。
Example/Demo (For your csv example in Question) - 范例/演示(针对您在问题中的csv范例)-
In [12]: df = pd.read_csv('a.csv',dtype={'Date':pd.datetime,'Name':str})
In [13]: df
Out[13]:
Date Name
0 2015-01-01 16:30:00.0 John
1 2015-02-11 16:30:00.0 Doe
2 2015-03-01 16:30:00.0 Sam
3 2015-03-05 16:30:00.0 Sam
4 2015-04-21 16:30:00.0 Chris
5 2015-05-07 16:30:00.0 John
6 2015-06-08 16:30:00.0 Doe
In [15]: df.groupby(['Name']).max()
Out[15]:
Date
Name
Chris 2015-04-21 16:30:00.0
Doe 2015-06-08 16:30:00.0
John 2015-05-07 16:30:00.0
Sam 2015-03-05 16:30:00.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.