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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。
