python pandas从时间序列中提取唯一日期

标签 python datetime dataframe pandas time-series

我有一个包含大量日内数据的 DataFrame,DataFrame 有几天的数据,日期不连续。

 2012-10-08 07:12:22            0.0    0          0  2315.6    0     0.0    0
 2012-10-08 09:14:00         2306.4   20  326586240  2306.4  472  2306.8    4
 2012-10-08 09:15:00         2306.8   34  249805440  2306.8  361  2308.0   26
 2012-10-08 09:15:01         2308.0    1   53309040  2307.4   77  2308.6    9
 2012-10-08 09:15:01.500000  2308.2    1  124630140  2307.0  180  2308.4    1
 2012-10-08 09:15:02         2307.0    5   85846260  2308.2  124  2308.0    9
 2012-10-08 09:15:02.500000  2307.0    3  128073540  2307.0  185  2307.6   11
 ......
 2012-10-10 07:19:30            0.0    0          0  2276.6    0     0.0    0
 2012-10-10 09:14:00         2283.2   80   98634240  2283.2  144  2283.4    1
 2012-10-10 09:15:00         2285.2   18  126814260  2285.2  185  2285.6    3
 2012-10-10 09:15:01         2285.8    6   98719560  2286.8  144  2287.0   25
 2012-10-10 09:15:01.500000  2287.0   36  144759420  2288.8  211  2289.0    4
 2012-10-10 09:15:02         2287.4    6  109829280  2287.4  160  2288.6    5
 ......

如何从上述 DataFrame 中提取日期时间格式的唯一日期?得到类似 [2012-10-08, 2012-10-10]

的结果

最佳答案

如果你有一个 Series 像:

In [116]: df["Date"]
Out[116]: 
0           2012-10-08 07:12:22
1           2012-10-08 09:14:00
2           2012-10-08 09:15:00
3           2012-10-08 09:15:01
4    2012-10-08 09:15:01.500000
5           2012-10-08 09:15:02
6    2012-10-08 09:15:02.500000
7           2012-10-10 07:19:30
8           2012-10-10 09:14:00
9           2012-10-10 09:15:00
10          2012-10-10 09:15:01
11   2012-10-10 09:15:01.500000
12          2012-10-10 09:15:02
Name: Date

其中每个对象都是一个时间戳:

In [117]: df["Date"][0]
Out[117]: <Timestamp: 2012-10-08 07:12:22>

调用.date()只能获取日期:

In [118]: df["Date"][0].date()
Out[118]: datetime.date(2012, 10, 8)

和 Series 有一个 .unique() 方法。所以你可以使用 map 和一个 lambda:

In [126]: df["Date"].map(lambda t: t.date()).unique()
Out[126]: array([2012-10-08, 2012-10-10], dtype=object)

或者使用Timestamp.date方法:

In [127]: df["Date"].map(pd.Timestamp.date).unique()
Out[127]: array([2012-10-08, 2012-10-10], dtype=object)

关于python pandas从时间序列中提取唯一日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14673394/

相关文章:

php - Laravel 5.6 将日期时间保存到数据库

r - 如何处理 “write.xlsx”错误: arguments imply differing number of rows

python - 在项目本地安装 Python 依赖

ajax - UTC日期时间问题

python - psycopg2.DataError : invalid input syntax for integer: "test" Getting error when moving code to test server

python - 在不同的 Windows 版本上使用 pickle 反序列化日期时间对象

r - 从另一个包含基于列的分层分类法的数据框架创建一个数据框架

python-3.x - 加速 Pandas 迭代

python - 将 Dataframe 列中的列表拆分为特定的列名称

Python Pandas – 如何抑制 PerformanceWarning?