alexa99
alexa99

Reputation: 23

how to use periodindex to the column name

use periodindex as my new column name and add values.

I have a dataframe which seems like:

A  B  C   D  
0  a  1  2  32  
1  b  3  4  33  
2  c  5  6  34  


timelist=['2010-01','2010-02',...]

I convert the timelist to quarter by:

periods=pd.PeriodIndex(timelist,freq="Q")

results:

PeriodIndex(['2000Q1', '2000Q1', '2000Q1', '2000Q2', '2000Q2', '2000Q2','2000Q3', '2000Q3', '2000Q3', '2000Q4', ...

what I want is:

a. simplify the periods into

 PeriodIndex(['2000Q1','2000Q2','2000Q3',...

(but do not turn it into string)

b.can i use the periods as new column names to the dataframe while put values in it?

something like:

x=0
for i in periods:
    df[i]=df.iloc[:,x:x+3].mean(axis=1)
    x=x+3
(but it failed)

Upvotes: 2

Views: 1219

Answers (2)

tawab_shakeel
tawab_shakeel

Reputation: 3739

timelist=['2010-01','2010-02','2010-03']
periods =  [i.split("-")[0]+"-"+"Q"+i.split("-")[-1][-1]for i in timelist]

# pd.PeriodIndex require list in the format ['2019-Q1'] your list contains ['2019-01'] so 01 was considered as quarter

periods= pd.PeriodIndex(periods,freq="Q")
print(periods)
PeriodIndex(['2010Q1', '2010Q2', '2010Q3'], dtype='period[Q-DEC]', freq='Q-DEC')

b part

Your code is working on my Data just convert i into string when storing as column

#I took sample data and it worked the way you wrote the code
import pandas_datareader as dr

df = dr.data.get_data_yahoo('btc-usd',start = '01-01-2015', end= '31-12-2018')
df.reset_index(inplace=True)

x=0
for i in periods:
    df[str(i)]=df.iloc[:,x:x+3].mean(axis=1)
    x=x+3

print(df)
       Close    Volume     AdjClose   2010Q1    2010Q2            2010Q3
0   318.239990  6472822 318.239990  313.990005  2.157817e+06    7.194831e+05
1   314.890015  4073067 314.890015  317.449997  1.357900e+06    4.528441e+05

Upvotes: 0

Nikesh Prasad
Nikesh Prasad

Reputation: 51

a. The data type of the output pd.PeriodIndex() is object which is used for strings in pandas.

b. You can create a new column in your dataframe like this:

df["periods"]=pd.PeriodIndex(timelist,freq="Q")

It will create a new column "periods", whose dtype is object which you can check like this:

df["periods"].dtype

Upvotes: 1

Related Questions