700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > python中convert函数用法_Python Pandas DataFrame.tz_convert用法及代码示例

python中convert函数用法_Python Pandas DataFrame.tz_convert用法及代码示例

时间:2022-03-06 09:09:00

相关推荐

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('-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('-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()函数已成功将给定数据帧中所需级别的时区转换为所需时区。

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。