Pandas 获取日期的天数
Pandas是一种流行的用于数据分析和处理的Python库。在使用Python Pandas进行数据分析和处理时,处理日期和时间是一项常见任务。从给定日期获取天数是一个现实生活中许多开发者可能遇到的任务。Pandas提供了许多函数和方法,使得执行此任务变得更加简单。了解如何从日期中获取天数在许多情况下非常有帮助。在本文中,我们将探讨在Pandas中确定星期几的几种方法。到本文结束时,您应该对使用Pandas从日期中提取星期几在您的项目中有一个扎实的理解。
可以使用以下方法来完成该任务:
方法
- 使用dt.dayofweek
- 
使用pd.to_datetime()和dt.day_name() 
- 
在多个日期字符串上使用pd.to_datetime()和dt.day_name() 
- 
在多个日期字符串上使用pd.dayofweek和dt.strftime() 
现在让我们讨论每种方法以及它们如何用于从Pandas中获取日期的天数。
方法1:使用dt.dayofweek
我们可以使用dt.dayofweek属性将给定的日期转换为其特定的星期几,然后通过创建一个手动映射将其转换为字符串形式。
步骤
- 导入必要的库
- 
使用pd.date_range()函数创建一个日期范围对象,提供开始和结束日期作为参数。 
- 
使用日期范围对象创建一个DataFrame 
- 
在DataFrame中添加一个新列来存储星期几的天数 
- 
使用dt.dayofweek属性从存储在DataFrame中的每个日期中获取星期几的天数 
- 
使用map()方法将星期几的天数映射到其名称,提供一个字典作为参数。 
- 
打印结果的DataFrame。 
步骤1 – 创建一个日期范围
dates = pd.date_range(start='2022-01-01', end='2022-01-07')
步骤2 – 使用日期范围创建一个数据帧
df = pd.DataFrame({'date': dates})
步骤3 – 添加一列显示星期几
df['day_of_week'] = df['date'].dt.dayofweek
步骤4 – 将星期几的数字映射为对应的名称
df['day_of_week'] = df['day_of_week'].map({
    0: 'Monday',
    1: 'Tuesday',
    2: 'Wednesday',
    3: 'Thursday',
    4: 'Friday',
    5: 'Saturday',
    6: 'Sunday'
})
步骤5 – 打印输出
print(df.head())
示例
import pandas as pd
# create a date range
dates = pd.date_range(start='2022-01-01', end='2022-01-07')
# create a DataFrame with the dates
df = pd.DataFrame({'date': dates})
# add a column with the day of the week
df['day_of_week'] = df['date'].dt.dayofweek
# map the day of the week number to its name
df['day_of_week'] = df['day_of_week'].map({
    0: 'Monday',
    1: 'Tuesday',
    2: 'Wednesday',
    3: 'Thursday',
    4: 'Friday',
    5: 'Saturday',
    6: 'Sunday'
})
# print the output
print(df.head())
输出
date      day_of_week
0 2022-01-01    Saturday
1 2022-01-02      Sunday
2 2022-01-03      Monday
3 2022-01-04     Tuesday
4 2022-01-05   Wednesday
方法2:使用pd.to_datetime()和dt.day_name()
我们可以使用dt.datetime()先将一个数据框的日期转换为日期时间对象,然后从该日期时间对象获取星期几。
步骤
- 导入pandas库
- 
创建一个包含日期字符串的数据框 
- 
使用pd.to_datetime()函数将日期字符串转换为相应的日期时间对象 
- 
添加一个新列到数据框中来存储星期几 
- 
使用dt.day_name()属性从日期时间对象中获取相应的星期几的名称 
- 
打印结果数据框以获取输出。 
示例
# Import the pandas library
import pandas as pd
# Create a DataFrame with a single date string
date_obj = pd.DataFrame({'Date': ['2023-04-10']})
# Convert the date string to a datetime object using the to_datetime() function
date_obj['Date'] = pd.to_datetime(date_obj['Date'])
# Add a new column to the DataFrame to store the day of the week
date_obj['Day'] = date_obj['Date'].dt.day_name()
# Print the resulting DataFrame
print(date_obj)
输出
Date     Day
0 2023-04-10  Monday
方法3:使用pd.to_datetime()和dt.day_name()方法处理多个日期字符串
我们可以使用dt.datetime()先将DataFrame中的日期转换为日期时间对象,然后从该日期时间对象中获取星期几。
步骤
- 导入pandas库
- 
创建一个包含多个日期字符串的DataFrame 
- 
使用pd.to_datetime()函数将日期字符串转换为对应的日期时间对象 
- 
在DataFrame中添加一个新的列来存储星期几的信息 
- 
使用dt.day_name()属性从DataFrame中的每个日期时间对象中提取星期几的名称 
- 
打印输出结果的DataFrame 
示例
# Import the pandas library
import pandas as pd
# Create a DataFrame with multiple date strings
dates = pd.DataFrame({'Date':['2019-03-07', '2020-03-07',
   '2021-03-07', '2022-03-07',
   '2023-03-07']})
# Convert the date strings to datetime objects using the pd.to_datetime() function
dates['Date'] = pd.to_datetime(dates['Date'])
# Add a new column to the DataFrame to store the day of the week
dates['Day'] = dates['Date'].dt.day_name()
# Print the resulting DataFrame 
print(dates)
输出
Date       Day
0 2019-03-07  Thursday
1 2020-03-07  Saturday
2 2021-03-07    Sunday
3 2022-03-07    Monday
4 2023-03-07   Tuesday
方法4:在多个日期字符串上使用pd.dayofweek和dt.strftime()
在这种方法中,我们使用dayofweek属性来获取日期字符串的星期几编号,然后使用strftime()函数将星期几的名称转化为字符串并进行缩写。
- 导入pandas库
- 
创建一个包含单个日期字符串的DataFrame 
- 
将日期字符串转化为日期时间对象 
- 
为DataFrame添加一列,以数值形式存储星期几 
- 
为DataFrame添加一列,以缩写形式存储星期几的名称 
- 
打印结果DataFrame 
示例
import pandas as pd
# Create a DataFrame with a single date string
date_obj = pd.DataFrame({'Date':['2023-04-10']})
# Convert the date string to a datetime object
date_obj['Date'] = pd.to_datetime(date_obj['Date'])
# Add a new column to the DataFrame to store the day of the week as a number
date_obj['DayNumber'] = date_obj['Date'].dt.dayofweek
# Add a new column to the DataFrame to store the abbreviated name of the day of the week
date_obj['DayOfWeek'] = date_obj['Date'].dt.strftime('%a')
# Print the resulting Dataframe
print(date_obj)
输出
Date  DayNumber DayOfWeek
0 2023-04-10          0       Mon
结论
通过使用这些方法,我们还可以轻松地向DataFrame中添加新列,以存储星期几和更多日期相关的信息。
每种方法或函数都有其自己的优缺点。根据您想要的表达式的复杂性以及您个人偏好编写代码的方式,您可以选择您想要的方法。
 极客笔记
极客笔记