Pandas DataFrame是带有标签轴(行和列)的二维大小可变的,可能是异构的表格数据结构。算术运算在行和列标签上对齐。可以将其视为Series对象的dict-like容器。这是 Pandas 的主要数据结构。
 Pandas  DataFrame.tz_convert()用于将tz-aware轴转换为目标时区。
用法: DataFrame.tz_convert(tz, axis=0, level=None, copy=True)
参数:
tz:字符串或pytz.timezone对象
axis:转换轴
level:如果轴为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()函数将给定 DataFrame 的时区转换为“欧洲/柏林”。
# 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()函数可将给定 DataFrame 中的MultiIndex级别1的时区转换为“欧洲/柏林”。
# 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()函数已成功将给定数据帧中所需级别的时区转换为所需时区。
相关用法
- Python pandas.map()用法及代码示例
- Python Pandas Series.str.len()用法及代码示例
- Python Pandas.factorize()用法及代码示例
- Python Pandas TimedeltaIndex.name用法及代码示例
- Python Pandas dataframe.ne()用法及代码示例
- Python Pandas Series.between()用法及代码示例
- Python Pandas DataFrame.where()用法及代码示例
- Python Pandas Series.add()用法及代码示例
- Python Pandas.pivot_table()用法及代码示例
- Python Pandas Series.mod()用法及代码示例
- Python Pandas Dataframe.at[ ]用法及代码示例
- Python Pandas Dataframe.iat[ ]用法及代码示例
- Python Pandas.pivot()用法及代码示例
- Python Pandas dataframe.mul()用法及代码示例
- Python Pandas.melt()用法及代码示例
注:本文由纯净天空筛选整理自Shubham__Ranjan大神的英文原创作品 Python | Pandas DataFrame.tz_convert。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
