如何使用Pandas从Excel文件列中提取时间数据

如何使用Pandas从Excel文件列中提取时间数据

在这些文章中,我们将讨论如何使用Pandas从Excel文件列中提取时间数据。假设我们的Excel文件看起来像下面给出的图片,那么我们必须从Excel表的列中提取时间,并将其存储到一个新的Dataframe列。

如何使用Pandas从Excel文件列中提取时间数据?

步骤:

  • 导入所需的模块。
  • 从Excel文件导入数据。
  • 为商店的提取时间多做一列。
  • 设置索引,用于搜索提取列。
  • 定义时间格式的模式(HH: MM: SS)。
  • 搜索时间并将其分配给数据框架中的相应列。

让我们来看看一步一步的实施情况。

第1步:导入所需的模块并从Excel文件中读取数据。

# importing required module
import pandas as pd;
import re;
  
# Read excel file and store in to DataFrame
data = pd.read_excel("time_sample_data.xlsx");
  
print("Original DataFrame")
data

输出:

如何使用Pandas从Excel文件列中提取时间数据?

步骤2:制作一个额外的列来存储时间数据。

# Create column for Time
data['New time'] = None
data

输出:

如何使用Pandas从Excel文件列中提取时间数据?

第3步:设置搜索的索引

# set index
index_set = data.columns.get_loc('Description')
index_time = data.columns.get_loc('New time')
  
print(index_set, index_time)

输出:

1 2

第4步:定义时间的正则表达式(regex)。

时间HH/MM/SS格式的Regex。

[0-24]{2}\:[0-60]{2}\:[0-60]{2}.

# define time pattern
time_pattern = r'([0-24]{2}\:[0-60]{2}\:[0-60]{2})'

步骤5:搜索时间并将其分配给数据框架中的相应列。

为了在一个字符串中使用regex搜索时间,我们使用re库的re.search()函数。

# searching the entire DataFrame
# with Time pattern
for row in range(0, len(data)):
    
    time = re.search(time_pattern,
                     data.iat[row,index_set]).group()
      
    data.iat[row, index_time] = time
      
print("Final DataFrame")    
data

输出:

如何使用Pandas从Excel文件列中提取时间数据?

完整代码:

# importing required module
import pandas as pd;
import re;
  
data = pd.read_excel("time_sample_data.xlsx");
print("Original DataFrame")
print(data)
  
# Create column for Date
data['New time']= None
print(data)
  
# set index
index_set= data.columns.get_loc('Description')
index_time=data.columns.get_loc('New time')
print(index_set,index_time)
  
# define the time pattern in HH:MM:SS
time_pattern= r'([0-24]{2}\:[0-60]{2}\:[0-60]{2})'
  
#searching dataframe with time pattern
for row in range(0, len(data)):
    time= re.search(time_pattern,data.iat[row,index_set]).group()
    data.iat[row,index_time] = time
      
print("\n Final DataFrame")    
data

输出:

如何使用Pandas从Excel文件列中提取时间数据?

注意:在运行这个程序之前,确保你已经在你的Python环境中安装了xlrd库。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程