python中convert函数用法_Python Pandas DataFrame.tz_convert用法及代码示例
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中convert函数用法_Python Pandas DataFrame.tz_convert用法及代码示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Java 将byte转换kb_【Java
- 下一篇: mongodb创建local库用户_mo