Python Pandas DataFrame.tz_localize

Python Pandas DataFrame.tz_localize

Pandas DataFrame是一个二维的大小可变的、可能是异质的表格数据结构,具有标记的axis(行和列)。算术操作在行和列的标签上对齐。它可以被认为是一个类似于Dict的系列对象的容器。这是Pandas的主要数据结构。Pandas DataFrame.tz_localize()函数将系列或DataFrame的tz-naive索引定位到目标时区。这个操作将索引本地化。

语法: DataFrame.tz_localize(tz, axis=0, level=None, copy=True, ambiguous='raise', nonexistent='raise')

参数:tz :字符串或pytz.timezone对象

axis :要本地化的axis

level :如果axis是一个MultiIndex,本地化一个特定级别。否则必须是None

copy :也会对基础数据进行复制

ambiguous :当时钟由于DST而向后移动时,可能会出现模糊的时间

nonexistent :在时钟由于DST而向前移动的特定时区不存在一个不存在的时间

返回值 :与输入的类型相同。

示例#1:使用DataFrame.tz_localize()函数将数据框架的给定tz-naive索引定位到目标时区。

# importing pandas as pd
import pandas as pd
 
# Creating the DataFrame
df = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],
                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],
                   'Age':[14, 25, 55, 8, 21]})
 
# Create the index
index_ = pd.date_range('2010-10-09 08:45', periods = 5, freq ='H', tz = 'US / Central')
 
# Set the index
df.index = index_
 
# Print the DataFrame
print(df)
Python

输出 :

Python Pandas DataFrame.tz_localize

现在我们将使用DataFrame.tz_localize()函数将数据框架的给定tz-naive索引本地化为 “欧洲/柏林 “时区。

# Let's find out the current timezone
# of the given dataframe
print(df.index)
 
# Let's localize the timezone of the
# dataframe index to 'Europe / Berlin'
df = df = df.tz_localize(tz = 'Europe / Berlin')
 
# Let's find out the current timezone
# of the given dataframe
print(df.index)
Python

输出 :

Python Pandas DataFrame.tz_localize

Python Pandas DataFrame.tz_localize

我们可以在输出中看到,DataFrame.tz_localize()函数已经成功将给定数据框架的tz-naive指数定位到目标时区。

示例#2 :使用DataFrame.tz_localize()函数将给定数据框架的tz-naive指数本地化。给定数据框架的索引是一个MultiIndex。

# importing pandas as pd
import pandas as pd
 
# Creating the DataFrame
df = pd.DataFrame({'Weight':[45, 88, 56, 15, 71],
                   'Name':['Sam', 'Andrea', 'Alex', 'Robin', 'Kia'],
                   'Age':[14, 25, 55, 8, 21]})
 
# Create the MultiIndex
index_ = pd.MultiIndex.from_product([['Date'], pd.date_range('2010-10-09 08:45', periods = 5, freq ='H')],
           names =['Level 1', 'Level 2'])
 
# Set the index
df.index = index_
 
# Print the DataFrame
print(df)
Python

输出 :

Python Pandas DataFrame.tz_localize

现在我们将使用DataFrame.tz_localize()函数将给定数据帧的tz-naive索引本地化为’US/Central’。

# Let's find out the current timezone
# of the Level 1 of the given dataframe
print(df.index[1])
 
# Let's localize the timezone of the
# level 1 of the dataframe to 'US / Central'
df = df.tz_localize(tz = 'US / Central', level = 1)
 
# Let's find out the current timezone
# of the level 1 of the given dataframe
print(df.index[1])
Python

输出 :

Python Pandas DataFrame.tz_localize

Python Pandas DataFrame.tz_localize

我们可以在输出中看到,DataFrame.tz_localize()函数已经成功将给定数据框架的tz-naive索引定位为’US/Central’。

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程

登录

注册