Python Pandas DataFrame.tz_convert
Pandas DataFrame是一个二维的大小可变的、可能是异质的表格数据结构,具有标记的axis(行和列)。算术操作在行和列的标签上对齐。它可以被认为是一个类似于Dict的系列对象的容器。这是Pandas的主要数据结构。Pandas DataFrame.tz_convert()函数用于将tz意识到的axis转换成目标时区。
语法: DataFrame.tz_convert(tz, axis=0, level=None, copy=True)
参数:tz :字符串或pytz.timezone对象
axis :要转换的axis
level :如果axis是一个MultiIndex,转换一个特定级别。否则必须是None
copy :也会复制一个基础数据
返回值 : tz转换的数据框架
示例#1:使用DataFrame.tz_convert()函数来转换给定数据帧的时区。
# 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_convert()函数将给定数据帧的时区转换成’欧洲/柏林’。
# Let's find out the current timezone
# of the given dataframe
print(df.index)
# Let's convert the timezone of the
# dataframe to 'Europe / Berlin'
df = df.tz_convert(tz = 'Europe / Berlin')
# Let's find out the current timezone
# of the given dataframe
print(df.index)
输出 :
我们可以在输出中看到,DataFrame.tz_convert()函数已经成功地将给定数据框架的时区转换为所需的时区。
示例#2 :使用DataFrame.tz_convert()函数转换给定数据框架的时区。给定数据框架的索引是一个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', tz =
'US/Central')], names =['Level 1', 'Level 2'])
# Set the index
df.index = index_
# Print the DataFrame
print(df)
输出 :
现在我们将使用DataFrame.tz_convert()函数将给定数据框架中MultiIndex的第1级的时区转换为’Europe/Berlin’。
# Let's find out the current timezone
# of the Level 1 of the given dataframe
print(df.index[1])
# Let's convert the timezone of the
# level 1 of the dataframe to 'Europe / Berlin'
df = df.tz_convert(tz = 'Europe/Berlin', level = 1)
# Let's find out the current timezone
# of the level 1 of the given dataframe
print(df.index[1])
输出 :
我们可以在输出中看到,DataFrame.tz_convert()函数已经成功地将给定数据框架中的所需等级的时区转换为所需时区。