个性化阅读
专注于IT技术分析

Python Pandas时间戳替换

Python是进行数据分析的一种出色语言, 主要是因为以数据为中心的python软件包具有奇妙的生态系统。大熊猫是这些软件包之一, 使导入和分析数据更加容易。

大熊猫Timestamp.replace()函数用于替换给定时间戳的成员值。该函数实现datetime.replace, 并且还处理纳秒。

语法:Timestamp.replace()参数:年:整数月份:整数日:整数小时:整数分钟:整数秒:整数微秒:整数纳秒:整数tzinfo:整数折叠:整数返回:替换字段的时间戳

示例1:采用Timestamp.replace()函数替换给定时间戳中的年份值。

# importing pandas as pd
import pandas as pd
  
# Create the Timestamp object
ts = pd.Timestamp(year = 2011 , month = 11 , day = 21 , hour = 10 , second = 49 , tz = 'US/Central' )
  
# Print the Timestamp object
print (ts)

输出:

Python Pandas时间戳替换1

现在我们将使用Timestamp.replace()函数将对象中的当前年份替换为2019。

# replace year
ts.replace(year = 2019 )

输出:

Python Pandas时间戳替换2

正如我们在输出中看到的, Timestamp.replace()函数已返回年值等于2019的Timestamp对象。

示例2:采用Timestamp.replace()函数可替换给定时间戳记中的年, 月和小时值。

# importing pandas as pd
import pandas as pd
  
# Create the Timestamp object
ts = pd.Timestamp(year = 2009 , month = 5 , day = 31 , hour = 4 , second = 49 , tz = 'Europe/Berlin' )
  
# Print the Timestamp object
print (ts)

输出:

Python Pandas时间戳替换3

现在我们将使用Timestamp.replace()函数替换对象中的当前年, 月和小时值。

# replace year, month and hour value
ts.replace(year = 2019 , month = 12 , hour = 1 )

输出:

Python Pandas时间戳替换4

正如我们在输出中看到的, Timestamp.replace()函数已返回一个Timestamp对象, 其年份值等于2019, 月份值等于12, 小时值等于1。

首先, 你的面试准备可通过以下方式增强你的数据结构概念:Python DS课程。


赞(0)
未经允许不得转载:srcmini » Python Pandas时间戳替换

评论 抢沙发

评论前必须登录!