Pandas 数据帧中的列类型从字符串转换为日期时间格式

当我们在 Python 的 Pandas DataFrame 中处理数据时,经常会遇到时间序列数据。Panday 是一个强大的工具,可以在 Python 中处理时间序列数据,我们可能需要在给定的数据集中将字符串转换为 Datetime 格式。

在本教程中,我们将学习如何将字符串的 DataFrame 列转换为日期时间格式“dd/mm/yy”。如果日期不是所需的格式,用户就不能对其执行任何基于时间序列的操作。为了解决这个问题,我们需要将日期转换成所需的日期时间格式。

Python 中转换数据类型格式的不同方法:

在本节中,我们将讨论将 Pandas DataFrame 列的数据类型从字符串更改为日期时间的不同方法:

方法 1:使用 pandas.to_datetime()函数

在这种方法中,我们将使用“pandas.to_datetime()”函数来转换 Pandas DataFrame 列中的数据类型。

示例:


import pandas as pnd

# Creating the dataframe
data_frame = pnd.DataFrame({'Date':['12/05/2021', '11/21/2018', '01/12/2020'],
                'Event':['Music- Dance', 'Poetry- Songs', 'Theatre- Drama'],
                'Cost':[15400, 7000, 25000]})

# Print the dataframe
print ("The data is: ") 
print (data_frame)

# Here, we are checking the data type of the 'Date' column
data_frame.info()

输出:

The data is: 
         Date           Event                     Cost
0  12/05/2021    Music- Dance  15400
1  11/21/2018   Poetry- Songs   7000
2  01/12/2020  Theatre- Drama  25000
 RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   Date    3 non-null      object 

1   Event   3 non-null      object
 2   Cost    3 non-null      int64 
dtypes: int64(1), object(2)
memory usage: 200.0+ bytes 

在这里,在输出中,我们可以看到数据帧中“日期”列的数据类型是“对象”,这意味着它是一个字符串。现在,我们将使用“pnd.to_datetime()”函数将数据类型转换为日期时间格式:


import pandas as pnd

# Creating the dataframe
data_frame = pnd.DataFrame({'Date':['12/05/2021', '11/21/2018', '01/12/2020'],
                'Event':['Music- Dance', 'Poetry- Songs', 'Theatre- Drama'],
                'Cost':[15400, 7000, 25000]})

# Print the dataframe
print ("The data is: ") 
print (data_frame)

# For converting the 'Date' column of DataFrame into datetime format
data_frame['Date'] = pnd.to_datetime(data_frame['Date'])

# Here, we are checking the data type of the 'Date' column
data_frame.info()

输出:

The data is: 
         Date           Event                     Cost
0  12/05/2021    Music- Dance  15400
1  11/21/2018   Poetry- Songs   7000
2  01/12/2020  Theatre- Drama  25000
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype  
 ---  ------  --------------  -----         
 0   Date    3 non-null      datetime64[ns] 

1   Event   3 non-null      object        
 2   Cost    3 non-null      int64         
dtypes: datetime64[ns](1), int64(1), object(1)
memory usage: 200.0+ bytes

现在,我们可以看到数据帧中“数据”列的格式已经更改为日期时间格式。

方法 2:使用 DataFrame.astype()函数。

在这种方法中,我们将使用“DataFrame.astype()”函数来转换 Pandas DataFrame 列中的数据类型。

示例:


import pandas as pnd

# Creating the dataframe
data_frame = pnd.DataFrame({'Date':['12/05/2021', '11/21/2018', '01/12/2020'],
                'Event':['Music- Dance', 'Poetry- Songs', 'Theatre- Drama'],
                'Cost':[15400, 7000, 25000]})

# Print the dataframe
print ("The data is: ") 
print (data_frame)

# Here, we are checking the data type of the 'Date' column
data_frame.info()

输出:

The data is: 
         Date           Event                     Cost
0  12/05/2021    Music- Dance  15400
1  11/21/2018   Poetry- Songs   7000
2  01/12/2020  Theatre- Drama  25000
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype 
---  ------  --------------  ----- 
 0   Date    3 non-null      object 

1   Event   3 non-null      object
 2   Cost    3 non-null      int64 
dtypes: int64(1), object(2)
memory usage: 200.0+ bytes

在这里,在输出中,我们可以看到数据帧中“日期”列的数据类型是“对象”,这意味着它是一个字符串。现在,我们将使用“数据帧类型()”函数将数据类型转换为日期时间格式:


import pandas as pnd

# Creating the dataframe
data_frame = pnd.DataFrame({'Date':['12/05/2021', '11/21/2018', '01/12/2020'],
                'Event':['Music- Dance', 'Poetry- Songs', 'Theatre- Drama'],
                'Cost':[15400, 7000, 25000]})

# Print the dataframe
print ("The data is: ") 
print (data_frame)
# For converting the 'Date' column of DataFrame into datetime format
data_frame['Date'] = data_frame['Date'].astype('datetime64[ns]')

# Here, we are checking the data type of the 'Date' column
data_frame.info()

输出:

The data is: 
         Date           Event   Cost
0  12/05/2021    Music- Dance  15400
1  11/21/2018   Poetry- Songs   7000
2  01/12/2020  Theatre- Drama  25000
<class 'pandas.core.frame.DataFrame'>
RangeIndex: 3 entries, 0 to 2
Data columns (total 3 columns):
 #   Column  Non-Null Count  Dtype         
---  ------  --------------  -----         
 0   Date    3 non-null      datetime64[ns] 

1   Event   3 non-null      object        
 2   Cost    3 non-null      int64         
dtypes: datetime64[ns](1), int64(1), object(1)
memory usage: 200.0+ bytes

现在,我们可以看到,通过使用 data_frame[‘Date’],DataFrame 中“Data”列的格式已更改为 datetime 格式。astype(‘datetime64[ns])。

方法 3:

假设我们在 DataFrame 列中有一个“yymmdd”格式的日期,我们必须将其从字符串转换为日期时间格式。

示例:


import pandas as pnd

# Now, we will initialize the nested list with Dataset
play_list = [['210302', 67000], ['210901', 62000], ['210706', 61900],
            ['210402', 59000], ['210802', 74000], 
            ['210804', 54050], ['210109', 57650], ['210509', 67300], ['210209', 76600]]

# Creating a pandas DataFrame
data_frame = pnd.DataFrame(play_list,columns = ['Date','Patient Number'])

# Print the dataframe
print ("The data is: ") 
print (data_frame)

# Here, we are checking the data type of the 'Date' column
print (data_frame.dtypes)

输出:

The data is: 
     Date          Patient Number
0  210302           67000
1  210901           62000
2  210706           61900
3  210402           59000
4  210802           74000
5  210804           54050
6  210109           57650
7  210509           67300
8  210209           76600
 Date              object 

Patient Number     int64
dtype: object

这里,在输出中,我们可以看到数据帧中“日期”列的数据类型是“对象”,也就是说,它是字符串。现在,我们将使用“data frame[‘ Date ‘]= PND . to datetime(data _ frame[‘ Date ‘],format = ‘%y%m%d ‘)”函数将数据类型转换为 datetime 格式。


import pandas as pnd

# Now, we will initialize the nested list with Dataset
play_list = [['210302', 67000], ['210901', 62000], ['210706', 61900], 
            ['210402', 59000], ['210802', 74000], 
            ['210804', 54050], ['210109', 57650], ['210509', 67300], ['210209', 76600]]

# creating a pandas dataframe
data_frame = pnd.DataFrame(play_list,columns = ['Date','Patient Number'])

# Print the dataframe
print ("The data is: ") 
print (data_frame)

# For converting the 'Date' column of DataFrame into datetime format
data_frame['Date'] = pnd.to_datetime(data_frame['Date'], format = '%y%m%d')

# Here, we are checking the data type of the 'Date' column
print (data_frame.dtypes)

输出:

The data is: 
     Date         Patient Number
0  210302           67000
1  210901           62000
2  210706           61900
3  210402           59000
4  210802           74000
5  210804           54050
6  210109           57650
7  210509           67300
8  210209           76600
 Date              datetime64[ns] 

Patient Number             int64
dtype: object

在上面的代码中,我们通过使用“PND . to datetime(data frame[‘ Date ‘],format = ‘%y%m%d ‘)”函数,将“Date”列的数据类型从“object”更改为“datetime64[ns]”。

方法 4:

我们可以使用“pandas.to_datetime()”函数将多列从“string”转换为“datetime”格式,这意味着“YYYYMMDD”格式。


# Initializing the nested list with Data set
Dataset_list = [['20210612', 54000, '20210812'], 
               ['20210814', 65000, '20210614'], 
               ['20210316', 71500, '20210316'], 
               ['20210519', 45000, '20210119'], 
               ['20210221', 98000, '20210221'], 
               ['20210124', 23000, '20210724'], 
               ['20210929', 12000, '20210924']] 

# creating a pandas dataframe
data_frame = pnd.DataFrame(
  Dataset_list, columns = ['Treatment_starting_Date',
                         'Patients Number',
                         'Treatment_ending_Date'])

# Print the dataframe
print ("The data is: ") 
print (data_frame)

# Here, we are checking the data type of the 'Date' column
print (data_frame.dtypes)

输出:

The data is: 
  Treatment_starting_Date   Patients Number     Treatment_ending_Date
0   20210612                54000                20210812
1   20210814                65000                20210614
2   20210316                71500                20210316
3   20210519                45000                20210119
4   20210221                98000                20210221
5   20210124                23000                20210724
6   20210929                12000                20210924
 Treatment_starting_Date    object 

Patients Number             int64
 Treatment_ending_Date      object 

dtype: object

在这里,在输出中,我们可以看到数据帧中“日期”列的数据类型是“对象”,这意味着它是一个字符串。现在,我们将使用“pnd.to_datetime(data_frame[”],format = ‘%y%m%d ‘)函数将数据类型“Date”列转换为 datetime 格式。


import pandas as pnd

# Initializing the nested list with Data set
Dataset_list = [['20210612', 54000, '20210812'],
               ['20210814', 65000, '20210614'],
               ['20210316', 71500, '20210316'],
               ['20210519', 45000, '20210119'],
               ['20210221', 98000, '20210221'],
               ['20210124', 23000, '20210724'],
               ['20210929', 12000, '20210924']]

# creating a pandas dataframe
data_frame = pnd.DataFrame(
  Dataset_list, columns = ['Treatment_starting_Date',
                         'Patients Number',
                         'Treatment_ending_Date'])

# Print the dataframe
print ("The data is: ") 
print (data_frame)

# For converting the multiple columns of DataFrame into datetime format
data_frame['Treatment_starting_Date'] = pnd.to_datetime(
                          data_frame['Treatment_starting_Date'],
                          format = '%Y%m%d'
)
data_frame['Treatment_ending_Date'] = pnd.to_datetime(
                          data_frame['Treatment_ending_Date'],
                          format = '%Y%m%d'
)

# Here, we are checking the data type of the 'Date' column
print (data_frame.dtypes)

输出:

The data is: 
  Treatment_starting_Date  Patients Number Treatment_ending_Date
0                20210612            54000              20210812
1                20210814            65000              20210614
2                20210316            71500              20210316
3                20210519            45000              20210119
4                20210221            98000              20210221
5                20210124            23000              20210724
6                20210929            12000              20210924
 Treatment_starting_Date    datetime64[ns] 

Patients Number                     int64
 Treatment_ending_Date      datetime64[ns] 

dtype: object

在上面的输出中,我们可以看到“治疗开始日期”和“治疗结束日期”的数据类型已经通过使用“pnd.to_datetime()”函数更改为日期时间格式。

结论

在本教程中,我们学习了在 Python 中将 Pandas DataFrame 的列类型从字符串转换为日期时间的不同方法。


原创文章,作者:AE2NK,如若转载,请注明出处:https://www.506064.com/n/127496.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
AE2NKAE2NK
上一篇 2024-10-03 23:15
下一篇 2024-10-03 23:16

相关推荐

  • Python计算阳历日期对应周几

    本文介绍如何通过Python计算任意阳历日期对应周几。 一、获取日期 获取日期可以通过Python内置的模块datetime实现,示例代码如下: from datetime imp…

    编程 2025-04-29
  • int类型变量的细节与注意事项

    本文将从 int 类型变量的定义、声明、初始化、范围、运算和类型转换等方面,对 int 类型变量进行详细阐述和讲解,帮助读者更好地掌握和应用 int 变量。 一、定义与声明 int…

    编程 2025-04-29
  • Python字符串宽度不限制怎么打代码

    本文将为大家详细介绍Python字符串宽度不限制时如何打代码的几个方面。 一、保持代码风格的统一 在Python字符串宽度不限制的情况下,我们可以写出很长很长的一行代码。但是,为了…

    编程 2025-04-29
  • Python中将字符串转化为浮点数

    本文将介绍在Python中将字符串转化为浮点数的常用方法。在介绍方法之前,我们先来思考一下这个问题应该如何解决。 一、eval函数 在Python中,最简单、最常用的将字符串转化为…

    编程 2025-04-29
  • Java判断字符串是否存在多个

    本文将从以下几个方面详细阐述如何使用Java判断一个字符串中是否存在多个指定字符: 一、字符串遍历 字符串是Java编程中非常重要的一种数据类型。要判断字符串中是否存在多个指定字符…

    编程 2025-04-29
  • Python3定义函数参数类型

    Python是一门动态类型语言,不需要在定义变量时显示的指定变量类型,但是Python3中提供了函数参数类型的声明功能,在函数定义时明确定义参数类型。在函数的形参后面加上冒号(:)…

    编程 2025-04-29
  • Python学习笔记:去除字符串最后一个字符的方法

    本文将从多个方面详细阐述如何通过Python去除字符串最后一个字符,包括使用切片、pop()、删除、替换等方法来实现。 一、字符串切片 在Python中,可以通过字符串切片的方式来…

    编程 2025-04-29
  • Python基本数字类型

    本文将介绍Python中基本数字类型,包括整型、布尔型、浮点型、复数型,并提供相应的代码示例以便读者更好的理解。 一、整型 整型即整数类型,Python中的整型没有大小限制,所以可…

    编程 2025-04-29
  • 使用FFmpeg在Java中将MP3 URL转换为PCM

    本文介绍了使用FFmpeg在Java中将MP3 URL转换为PCM的具体步骤,以及相应代码示例。 一、准备工作 在使用FFmpeg之前,需要先安装FFmpeg,可以在官网(http…

    编程 2025-04-29
  • Python中的Bool类型判断

    本篇文章旨在讲解Python中的Bool类型判断。在Python中,Bool类型是经常使用的一种类型,因此掌握其用法非常重要。 一、True和False 在Python中,True…

    编程 2025-04-29

发表回复

登录后才能评论