Formatting Quarter time in pandas columns

I have DataFramewith columns in DateTimeindex representing quarters such as:

2000-03-31 00:00:00

How can I do to convert this to "2000q1"?

I looked through the docs, but they only say DateTimeIndex.quarter Here: http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DatetimeIndex.quarter.html

format='%Y%q'does not work. Also an optionon='%Y%q

+4
source share
1 answer

You can use to_period("Q"):

df.index = df.index.to_period("Q")

import pandas as pd
df = pd.DataFrame({"y": [1,2,3]}, 
                  index=pd.to_datetime(["2000-03-31 00:00:00", "2000-05-31 00:00:00", "2000-08-31 00:00:00"]))

df.index = df.index.to_period("Q")
df
#       y
#2000Q1 1
#2000Q2 2
#2000Q3 3

To convert a normal column col, use dtto access the objects Datetimein the series:

df = pd.DataFrame({"y": [1,2,3], 'col': pd.to_datetime(["2000-03-31 00:00:00", "2000-05-31 00:00:00", "2000-08-31 00:00:00"])})


df['col'] = df['col'].dt.to_period("Q")

df
#      col  y
#0  2000Q1  1
#1  2000Q2  2
#2  2000Q3  3
+7

Source: https://habr.com/ru/post/1665165/


All Articles