当前位置: 首页>>编程示例 >>用法及示例精选 >>正文


Python Pandas DataFrame.tz_localize用法及代码示例

Pandas DataFrame是带有标签轴(行和列)的二维大小可变的,可能是异构的表格数据结构。算术运算在行和列标签上对齐。可以将其视为Series对象的dict-like容器。这是 Pandas 的主要数据结构。

Pandas DataFrame.tz_localize()函数将Series或DataFrame的tz-naive索引本地化为目标时区。此操作将索引本地化。

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

参数:
tz:字符串或pytz.timezone对象
axis:定位轴
level:如果轴为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)

输出:

现在我们将使用DataFrame.tz_localize()函数将 DataFrame 的给定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) 

输出:

正如我们在输出中看到的,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)

输出:

现在我们将使用DataFrame.tz_localize()函数将给定 DataFrame 的tz-naive索引本地化为“美国/中央”。

# 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]) 

输出:

正如我们在输出中看到的,DataFrame.tz_localize()函数已成功将给定 DataFrame 的tz-naive索引本地化为“美国/中央”。



相关用法


注:本文由纯净天空筛选整理自Shubham__Ranjan大神的英文原创作品 Python | Pandas DataFrame.tz_localize。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。