Các mẫu theo thời gian

Phân tích dữ liệu khám phá trong Python

Izzy Weber

Curriculum Manager, DataCamp

Các mẫu theo thời gian

divorce = pd.read_csv("divorce.csv")
divorce.head()
  marriage_date  marriage_duration
0    2000-06-26                5.0
1    2000-02-02                2.0
2    1991-10-09                10.0
3    1993-01-02                10.0
4    1998-12-11                7.0               
Phân tích dữ liệu khám phá trong Python

Nhập dữ liệu DateTime

  • Cần khai báo rõ dữ liệu DateTime cho Pandas

 

divorce.dtypes
marriage_date         object
marriage_duration    float64
dtype: object
Phân tích dữ liệu khám phá trong Python

Nhập dữ liệu DateTime

divorce = pd.read_csv("divorce.csv", parse_dates=["marriage_date"])
divorce.dtypes
marriage_date        datetime64[ns]
marriage_duration           float64
dtype: object
Phân tích dữ liệu khám phá trong Python

Chuyển sang dữ liệu DateTime

  • pd.to_datetime() chuyển đối số thành dữ liệu DateTime

 

divorce["marriage_date"] = pd.to_datetime(divorce["marriage_date"])
divorce.dtypes
marriage_date        datetime64[ns]
marriage_duration           float64
dtype: object
Phân tích dữ liệu khám phá trong Python

Tạo dữ liệu DateTime

divorce.head(2)
   month  day  year  marriage_duration 
0      6   26  2000                5.0 
1      2    2  2000                2.0
divorce["marriage_date"] = pd.to_datetime(divorce[["month", "day", "year"]])
divorce.head(2)
    month  day  year  marriage_duration  marriage_date 

 0      6   26  2000                5.0     2000-06-26 
 1      2    2  2000                2.0     2000-02-02
Phân tích dữ liệu khám phá trong Python

Tạo dữ liệu DateTime

  • Trích xuất phần của ngày đầy đủ bằng các thuộc tính dt.month, dt.day, và dt.year
divorce["marriage_month"] = divorce["marriage_date"].dt.month
divorce.head()
    marriage_date  marriage_duration  marriage_month 
 0     2000-06-26                5.0               6 
 1     2000-02-02                2.0               2 
 2     1991-10-09               10.0              10 
 3     1993-01-02               10.0               1 
 4     1998-12-11                7.0              12
Phân tích dữ liệu khám phá trong Python

Trực quan hóa mẫu theo thời gian

sns.lineplot(data=divorce, x="marriage_month", y="marriage_duration")
plt.show()

Biểu đồ đường thể hiện mối quan hệ giữa tháng kết hôn và thời gian hôn nhân

Phân tích dữ liệu khám phá trong Python

Ayo berlatih!

Phân tích dữ liệu khám phá trong Python

Preparing Video For Download...