Pandas日期函数

gmxoilav  于 2023-03-06  发布在  其他
关注(0)|答案(2)|浏览(97)

给定一个Pandas DataFrame df,其中的'Date'列包含时间戳,编写一个Python函数来选择日期介于'2023 - 01 - 01'和'2023 - 01 - 31'之间的所有行。
这是我生成的数据

df12=pd.DataFrame(data=['2023-01-02 09:15:00','2023-03-02 15:25:02','2023-03-02 15:45:00','2023-01-02 05:55:00','2023-03-02 05:55:00'],columns=['Date'])
Date

0   2023-01-02 09:15:00
1   2023-03-02 15:25:02
2   2023-03-02 15:45:00
3   2023-01-02 05:55:00
4   2023-03-02 05:55:00
df12['Date'] = pd.to_datetime(df12['Date'])
df12['Date'].dt.date
start_date = '2023-01-01'
end_date = '2023-01-31'

date_range = pd.date_range(start=start_date, end=end_date)

for i in df12['Date'].dt.date:
    if i in date_range:
        print(i)

它什么也不返回,但实际上应该返回:

2023-01-02
2023-01-02
acruukt9

acruukt91#

您也可以使用datetime函数:

import pandas as pd
from datetime import datetime

def filter_dates(df, start_date, end_date):
    date_format = '%Y-%m-%d %H:%M:%S'
    start_date_str = start_date.strftime(date_format)
    end_date_str = end_date.strftime(date_format)
    filtered_df = df.loc[(df['Date'] >= start_date_str) & (df['Date'] <= end_date_str)]
    return filtered_df

df = pd.DataFrame(data=['2023-01-02 09:15:00','2023-03-02 15:25:02','2023-03-02 15:45:00','2023-01-02 05:55:00','2023-03-02 05:55:00'], columns=['Date'])
start_date = datetime(2023, 1, 1, 0, 0, 0)
end_date = datetime(2023, 1, 31, 0, 0, 0)

filtered_df = filter_dates(df, start_date, end_date)
print(filtered_df)

输出:

Date
0  2023-01-02 09:15:00
3  2023-01-02 05:55:00
kgsdhlau

kgsdhlau2#

您可以使用布尔掩码来选择行:

import pandas as pd

df = pd.DataFrame(data=['2023-01-02 09:15:00','2023-03-02 15:25:02','2023-03-02 15:45:00','2023-01-02 05:55:00','2023-03-02 05:55:00'],columns=['Date'])
df['Date'] = pd.to_datetime(df['Date'])
df['Date'].dt.date
start_date = '2023-01-01'
end_date = '2023-01-31'

print(df)
print()
print(df.loc[(df['Date'] >= start_date) & (df['Date'] <= end_date)])

输出:

Date
0 2023-01-02 09:15:00
1 2023-03-02 15:25:02
2 2023-03-02 15:45:00
3 2023-01-02 05:55:00
4 2023-03-02 05:55:00

                 Date
0 2023-01-02 09:15:00
3 2023-01-02 05:55:00

相关问题