Python| Pandas DataFrame.tz_localize
Pandas DataFrame 是一种二维大小可变的、潜在异构的表格数据结构,带有标记的轴(行和列)。算术运算在行标签和列标签上对齐。它可以被认为是 Series 对象的类 dict 容器。这是 Pandas 的主要数据结构。
Pandas DataFrame.tz_localize()
函数将 Series 或 DataFrame 的 tz-naive 索引本地化到目标时区。此操作本地化索引。
Syntax: DataFrame.tz_localize(tz, axis=0, level=None, copy=True, ambiguous=’raise’, nonexistent=’raise’)
Parameter :
tz : string or pytz.timezone object
axis : the axis to localize
level : If axis ia a MultiIndex, localize a specific level. Otherwise must be None
copy : Also make a copy of the underlying data
ambiguous : When clocks moved backward due to DST, ambiguous times may arise
nonexistent : A nonexistent time does not exist in a particular timezone where clocks moved forward due to DST
Returns : Same type as the input.
示例 #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()
函数将数据帧的给定 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()
函数将给定数据帧的 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])
输出 :
正如我们在输出中看到的, DataFrame.tz_localize()
函数已成功将给定数据帧的 tz-naive 索引本地化为“US/Central”。