■ DatetimeProperties 클래스의 to_period 메소드를 사용해 DataFrame 객체에서 두 날짜 컬럼 값 사이의 월 수를 갖는 신규 컬럼을 추가하는 방법을 보여준다.
▶ main.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
import pandas as pd dataFrame = pd.read_excel("tips.xlsx", index_col = 0) dataFrame["date1"] = pd.Timestamp("2013-01-15") dataFrame["date2"] = pd.Timestamp("2015-02-15") datetimeProperties1 = dataFrame["date1"].dt datetimeProperties2 = dataFrame["date2"].dt dataFrame["months_between"] = datetimeProperties2.to_period("M") - datetimeProperties1.to_period("M") print(dataFrame) """ total_bill tip sex smoker day time size date1 date2 months_between 0 16.99 1.01 Female No Sun Dinner 2 2013-01-15 2015-02-15 <25 * MonthEnds> 1 10.34 1.66 Male No Sun Dinner 3 2013-01-15 2015-02-15 <25 * MonthEnds> 2 21.01 3.50 Male No Sun Dinner 3 2013-01-15 2015-02-15 <25 * MonthEnds> 3 23.68 3.31 Male No Sun Dinner 2 2013-01-15 2015-02-15 <25 * MonthEnds> 4 24.59 3.61 Female No Sun Dinner 4 2013-01-15 2015-02-15 <25 * MonthEnds> .. ... ... ... ... ... ... ... ... ... ... 239 29.03 5.92 Male No Sat Dinner 3 2013-01-15 2015-02-15 <25 * MonthEnds> 240 27.18 2.00 Female Yes Sat Dinner 2 2013-01-15 2015-02-15 <25 * MonthEnds> 241 22.67 2.00 Male Yes Sat Dinner 2 2013-01-15 2015-02-15 <25 * MonthEnds> 242 17.82 1.75 Male No Sat Dinner 2 2013-01-15 2015-02-15 <25 * MonthEnds> 243 18.78 3.00 Female No Thur Dinner 2 2013-01-15 2015-02-15 <25 * MonthEnds> [244 rows x 10 columns] """ |
▶ requirements.txt
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
defusedxml==0.7.1 et_xmlfile==2.0.0 numpy==2.1.3 odfpy==1.4.1 openpyxl==3.1.5 pandas==2.2.3 python-calamine==0.2.3 python-dateutil==2.9.0.post0 pytz==2024.2 pyxlsb==1.0.10 six==1.16.0 tzdata==2024.2 xlrd==2.0.1 XlsxWriter==3.2.0 |
※ pip install "pandas[excel]" 명령을 실행했다.