Pandas DataFrame.to_period(~) 方法將源 DataFrame 的  DatetimeIndex  轉換為  PeriodIndex  。
參數
1.freq | string | optional
分配給新  PeriodIndex  的頻率。默認情況下,頻率是從  DatetimeIndex  推斷的。
2. axis | int 或 string | optional
是否轉換行索引或列索引:
| 軸 | 說明 | 
|---|---|
| 
 | 轉換行索引。 | 
| 
 | 轉換列索引。 | 
默認情況下,axis=0 。
3. copy | boolean | optional
- 
如果 True,則返回新的DataFrame。修改此 DataFrame 不會改變源 DataFrame,反之亦然。
- 
如果 False,則不會創建新的 DataFrame - 修改返回的 DataFrame 將改變源 DataFrame,反之亦然。
默認情況下,copy=True 。
返回值
DataFrame 和  PeriodIndex  。
例子
基本用法
考慮以下帶有  DatetimeIndex  的 DataFrame :
date_index = pd.date_range("2020/12/25", periods=3)
df = pd.DataFrame({"A":[2,3,4],"B":[5,6,7]}, index=date_index)
df
             A   B
2020-12-25   2   5
2020-12-26   3   6
2020-12-27   4   7要將索引從  DatetimeIndex  轉換為  PeriodIndex  :
df_period = df.to_period()
df_period
             A   B
2020-12-25   2   5
2020-12-26   3   6
2020-12-27   4   7要確認索引現在是 PeriodIndex :
df_period.index
PeriodIndex(['2020-12-25', '2020-12-26', '2020-12-27'], dtype='period[D]', freq='D')指定頻率參數
考慮與上麵相同的 df 和  DatetimeIndex  :
date_index = pd.date_range("2020/12/25", periods=3)
df = pd.DataFrame({"A":[2,3,4],"B":[5,6,7]}, index=date_index)
df
             A   B
2020-12-25   2   5
2020-12-26   3   6
2020-12-27   4   7要將索引從  DatetimeIndex  轉換為  PeriodIndex ,頻率為 "M"(月):
df_period = df.to_period(freq="M")
df_period
          A   B
2020-12   2   5
2020-12   3   6
2020-12   4   7請注意,由於頻率現在設置為幾個月,day-unit 已被刪除。
相關用法
- Python Pandas DataFrame to_csv方法用法及代碼示例
- Python Pandas DataFrame to_json方法用法及代碼示例
- Python Pandas DataFrame to_timestamp方法用法及代碼示例
- Python Pandas DataFrame to_numpy方法用法及代碼示例
- Python Pandas DataFrame to_dict方法用法及代碼示例
- Python PySpark DataFrame toDF方法用法及代碼示例
- Python PySpark DataFrame toJSON方法用法及代碼示例
- Python PySpark DataFrame toPandas方法用法及代碼示例
- Python Pandas DataFrame tz_convert方法用法及代碼示例
- Python Pandas DataFrame tail方法用法及代碼示例
- Python Pandas DataFrame transform方法用法及代碼示例
- Python Pandas DataFrame truncate方法用法及代碼示例
- Python Pandas DataFrame tz_localize方法用法及代碼示例
- Python Pandas DataFrame truediv方法用法及代碼示例
- Python Pandas DataFrame transpose方法用法及代碼示例
- Python Pandas DataFrame tshift方法用法及代碼示例
- Python Pandas DataFrame take方法用法及代碼示例
- Python PySpark DataFrame tail方法用法及代碼示例
- Python PySpark DataFrame transform方法用法及代碼示例
- Python PySpark DataFrame take方法用法及代碼示例
- Python Pandas DataFrame empty屬性用法及代碼示例
- Python Pandas DataFrame pop方法用法及代碼示例
- Python Pandas DataFrame nsmallest方法用法及代碼示例
- Python Pandas DataFrame sample方法用法及代碼示例
- Python Pandas DataFrame items方法用法及代碼示例
注:本文由純淨天空篩選整理自Isshin Inada大神的英文原創作品 Pandas DataFrame | to_period method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。
