Computer >> คอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

Python Pandas - สร้าง PeriodIndex และรับวันในสัปดาห์


ในการสร้าง PeriodIndex ให้ใช้ pandas.PeriodIndex() กระบวนการ. รับวันในสัปดาห์โดยใช้ PeriodIndex.dayofweek ทรัพย์สิน

ขั้นแรก นำเข้าไลบรารีที่จำเป็น -

import pandas as pd

สร้างวัตถุ PeriodIndex PeriodIndex เป็น ndarray ที่ไม่เปลี่ยนรูปซึ่งมีค่าลำดับซึ่งระบุช่วงเวลาปกติของเวลา เราได้ตั้งค่าความถี่โดยใช้พารามิเตอร์ "ความถี่" -

periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'], freq="D")

แสดงวัตถุ PeriodIndex -

print("PeriodIndex...\n", periodIndex)

แสดงวันในสัปดาห์จากวัตถุ PeriodIndex วันของสัปดาห์จะแสดงเป็น Monday=0, Tuesday=1 ... Sunday=6 −

print("\nDays of the week from the PeriodIndex...\n", periodIndex.dayofweek)

ตัวอย่าง

ต่อไปนี้เป็นรหัส -

import pandas as pd

# Create a PeriodIndex object
# PeriodIndex is an immutable ndarray holding ordinal values indicating regular periods in time
# We have set the frequency using the "freq" parameter
periodIndex = pd.PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20',
'2021-09-15', '2022-03-12', '2023-06-18'], freq="D")

# Display PeriodIndex object
print("PeriodIndex...\n", periodIndex)

# Display PeriodIndex frequency
print("\nPeriodIndex frequency...\n", periodIndex.freq)

# Display day from the PeriodIndex object
print("\nThe number of days from the PeriodIndex...\n", periodIndex.day)

# Display day of the week from the PeriodIndex object
# Days of week are displayed as Monday=0, Tuesday=1 ... Sunday=6
print("\nDays of the week from the PeriodIndex...\n", periodIndex.dayofweek)

ผลลัพธ์

สิ่งนี้จะสร้างรหัสต่อไปนี้ -

PeriodIndex...
PeriodIndex(['2018-07-25', '2019-10-30', '2020-11-20', '2021-09-15', '2022-03-12', '2023-06-18'],
dtype='period[D]')

PeriodIndex frequency...
<Day>

The number of days from the PeriodIndex...
Int64Index([25, 30, 20, 15, 12, 18], dtype='int64')

Days of the week from the PeriodIndex...
Int64Index([2, 2, 4, 2, 5, 6], dtype='int64')