[英]Python dataframe with date (dates and events)
Using PYTHON, I am trying to sort the values in the table based on dates and the associated events.使用 PYTHON,我试图根据日期和相关事件对表中的值进行排序。 Date1 and event1 are a pair because event1 occurred on date1.
Date1 和 event1 是一对,因为 event1 发生在 date1。 The same for other dates and events.
其他日期和事件也一样。 date1 is in a column of its own, and event1 is also in its own separate column.
date1 在它自己的列中,event1 也在它自己的单独列中。
For example, the table would include as below:例如,该表将包括如下内容:
date1![]() |
event1![]() |
date2![]() |
event2![]() |
date3![]() |
event3![]() |
---|---|---|---|---|---|
March 6, 2021 ![]() |
eventC![]() |
Jan. 1, 2020 ![]() |
eventX![]() |
May 11, 2020 ![]() |
eventB![]() |
Dec. 6, 2021 ![]() |
eventBB![]() |
Feb. 11, 2001 ![]() |
eventYY![]() |
June 13, 1990 ![]() |
eventSS![]() |
March 16, 2019 ![]() |
eventCD![]() |
Jan. 1, 1998 ![]() |
eventRE![]() |
May 23, 1989 ![]() |
eventDF![]() |
Nov. 1, 2008 ![]() |
eventCC![]() |
April 14, 2001 ![]() |
eventWQ![]() |
March 17, 1999 ![]() |
eventCV![]() |
I would like the result to show as follows where for each row, sort the data from oldest date to the newest, but the order of the events follow their respective dates (eg eventC that occurred on March 6, 2021 as the first in row 0 is now reordered to be the third in row 0).我希望结果显示如下,对于每一行,将数据从最早日期到最新日期排序,但事件的顺序遵循它们各自的日期(例如,2021 年 3 月 6 日发生的 eventC 作为第 0 行中的第一个现在重新排序为第 0 行中的第三个)。
date1![]() |
event1![]() |
date2![]() |
event2![]() |
date3![]() |
event3![]() |
---|---|---|---|---|---|
Jan. 1, 2020 ![]() |
eventX![]() |
May 11, 2020 ![]() |
eventB![]() |
March 6, 2021 ![]() |
eventC![]() |
June 13, 1990 ![]() |
eventSS![]() |
Feb. 11, 2001 ![]() |
eventYY![]() |
Dec. 6, 2021 ![]() |
eventBB![]() |
May 23, 1989 ![]() |
eventDF![]() |
Jan. 1, 1998 ![]() |
eventRE![]() |
March 16, 2019 ![]() |
eventCD![]() |
March 17, 1999 ![]() |
eventCV![]() |
Nov. 1, 2008 ![]() |
eventCC![]() |
April 14, 2001 ![]() |
eventWQ![]() |
I would like to keep the output in the table format as above.我想将 output 保留在上面的表格格式中。 (unless there is a good reason not to...) =)
(除非有充分的理由不...)=)
This is actually a very small version of a much larger data.这实际上是更大数据的一个非常小的版本。 Any help would be appreciated.
任何帮助,将不胜感激。 Thanks to all in advance!!!
提前感谢大家!!!
Cast the ' Dates
' values to datetime
and use the sort_values()
function. Example:将“
Dates
”值转换为datetime
时间并使用sort_values()
function。示例:
import pandas as pd
df = pd.DataFrame([{"Date":"02-01-1945","Name":"event2"},{"Date":"20-11-1934", "Name":"event1"}])
print(df)
#Output:
#
# Date Name
#0 02-01-1945 event2
#1 20-11-1934 event1
df["Date"] = pd.to_datetime(df["Date"])
df= df.sort_values(by="Date")
print(df)
#Output:
# Date Name
#1 1934-11-20 event1
#0 1945-02-01 event2
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.