当前位置 博文首页 > Python Pandas DataFrame.tz_convert用法及代码示例_亮点旅拍的

    Python Pandas DataFrame.tz_convert用法及代码示例_亮点旅拍的

    作者:[db:作者] 时间:2021-09-02 16:26

    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)

    输出:

    086abdac92e4d19a1d11b86bb605b5ad.png

    现在我们将使用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)

    输出:

    4c3f66d0f4d0781fff5d1c588a649b11.png

    97fbd2c44aa17ba31966050e3796f813.png

    正如我们在输出中看到的,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)

    输出:

    7a1baccc98caf2e5f3a82d4ab0619f27.png

    现在我们将使用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])

    输出:

    e732f78495d99a4def6d97a5d3f49482.png

    d009b2a36e3cc20f60c521fcfe1fa99f.png

    正如我们在输出中看到的,DataFrame.tz_convert()函数已成功将给定数据帧中所需级别的时区转换为所需时区。

    cs