Pandas 从日期时间列中分离月份和年份

Pandas 从日期时间列中分离月份和年份

在本文中,我们将介绍如何从Pandas日期时间列中分离出月份和年份。Pandas是一种开源数据分析工具,还具有读取数据的能力,支持多种文件格式,如CSV、Excel等。

阅读更多:Pandas 教程

Pandas日期时间列

在数据分析过程中,日期和时间信息在数据集中很常见,Pandas提供了灵活的日期时间列功能,用于处理时间序列数据。Pandas datetime列是Pandas数据框中的一种数据类型,需要使用Pandas的to_datetime()方法将字符串转换为datetime模式。

import pandas as pd

df = pd.DataFrame({
    'date_info': ['2021-01-01 07:30:00', '2021-01-02 12:00:00', '2021-01-03 18:30:00']
})

df['date_info'] = pd.to_datetime(df['date_info'])
print(df['date_info'])
Python

上述代码创建了一个数据框,其中包含一个日期时间信息的字符串列。使用Pandas to_datetime()方法将该列转换为Pandas datetime列,并输出结果:

0   2021-01-01 07:30:00
1   2021-01-02 12:00:00
2   2021-01-03 18:30:00
Name: date_info, dtype: datetime64[ns]
Python

从Pandas日期时间列中提取月份

Pandas提供了.dt属性,用于从日期时间列中提取月份。可以使用.dt.month属性从日期时间列中提取月份,返回一个新的Series对象,其中的月份信息包含在一个整数数组中。

import pandas as pd

df = pd.DataFrame({
    'date_info': ['2021-01-01 07:30:00', '2021-02-02 12:00:00', '2021-03-03 18:30:00']
})

df['date_info'] = pd.to_datetime(df['date_info'])
df['month'] = df['date_info'].dt.month
print(df['month'])
Python

上述代码创建了一个数据框,并使用Pandas to_datetime()方法将字符串列转换为Pandas datetime列。然后,使用.dt.month从日期时间列中提取月份信息,并将其存储在一个新的列中,最后输出该列的结果:

0    1
1    2
2    3
Name: month, dtype: int64
Python

从Pandas日期时间列中提取年份

类似地,Pandas还提供了一种从日期时间列中提取年份的方法。可以使用.dt.year属性从日期时间列中提取年份,返回一个新的Series对象,其中年份信息包含在一个整数数组中。

import pandas as pd

df = pd.DataFrame({
    'date_info': ['2021-01-01 07:30:00', '2022-02-02 12:00:00', '2023-03-03 18:30:00']
})

df['date_info'] = pd.to_datetime(df['date_info'])
df['year'] = df['date_info'].dt.year
print(df['year'])
Python

上述代码创建了一个数据框,并使用Pandas to_datetime()方法将字符串列转换为Pandas datetime列。然后,使用.dt.year从日期时间列中提取年份信息,并将其存储在一个新的列中,最后输出该列的结果:

0    2021
1    2022
2    2023
Name: year, dtype: int64
Python

从Pandas日期时间列中提取月份和年份

有时,需要同时从日期和时间列中提取月份和年份。可以将上述技术组合使用,从Pandas日期时间列中同时提取月份和年份。

import pandas as pd

df = pd.DataFrame({
    'date_info': ['2021-01-01 07:30:00', '2022-02-02 12:00:00', '2023-03-03 18:30:00']
})

df['date_info'] = pd.to_datetime(df['date_info'])
df['year'] = df['date_info'].dt.year
df['month'] = df['date_info'].dt.month
print(df[['year', 'month']])
Python

上述代码也创建了一个数据框,并使用Pandas to_datetime()方法将字符串列转换为Pandas datetime列。然后,同时使用.dt.year和.dt.month从日期时间列中提取年份和月份信息,并将它们存储在两个新列中,最后输出这两个列的结果:

   year  month
0  2021      1
1  2022      2
2  2023      3
Python

总结

本文介绍了如何从Pandas日期时间列中分离出月份和年份,同时给出了使用示例。这些技术对于处理时间序列数据非常有用,可以帮助我们更好地分析和理解数据。希望本文对您有所帮助。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册