Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting Quarter time in pandas columns

I have a DataFrame with columns in DateTime index, representing quarters such as: 2000-03-31 00:00:00

How can I do to transform this into '2000q1'?

I have looked around the docs, but they only mention DateTimeIndex.quarter

format='%Y%q' does not work. Neither does the option on='%Y%q

like image 872
B Furtado Avatar asked Dec 28 '16 20:12

B Furtado


People also ask

How do I change the datetime format in pandas DataFrame?

Use DataFrame. style. format() and Lambda Function to Change datetime Format. You can also use the DataFrame.


1 Answers

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 dt to access the Datetime objects in 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
like image 62
Psidom Avatar answered Oct 12 '22 10:10

Psidom