0

Thanks for investing time to help me out :)

I have DataFrame (df_NSE_Price_) like below:

Company Name                ID      2000-01-03 00:00:00 2000-01-04 00:00:00 ....
Reliance Industries Ltd.    100325  50.810              54.
Tata Consultancy Service    123455  123                 125
..

I would want output like below :

Company Name                ID      March 00   April 00 .....
Reliance Industries Ltd    100325   52         55
Tata Consultancy Services  123455   124.3      124
..

The output data has to have the average of data month wise.

So far i have tried

df_NSE_Price_.resample('M',axis=1).mean()

But this gave me error Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'Index'

2 Answers2

1

Something like this should work: df.transpose().resample('M',axis=1).mean().transpose()

Yash
  • 21
  • 4
  • Only valid with DatetimeIndex, TimedeltaIndex or PeriodIndex, but got an instance of 'RangeIndex' > gave the same error – Ritika Mehta Jul 25 '20 at 22:18
0

First, I converted the data to a Data Frame (I added a column with February info, too).

import pandas as pd

columns = ('Company Name', 
           'ID', 
           '2000-01-03 00:00:00', 
           '2000-01-04 00:00:00', 
           '2000-02-04 00:00:00')

data = [('Reliance Industries Ltd.', 100325, 50.810, 54., 66.0),
        ('Tata Consultancy Service', 123455, 123, 125, 130.0),]

df = pd.DataFrame(data=data, columns=columns)

Second, I created a two-level index (MultiIndex), using Company and ID. Now, all column labels are dates. Then, I converted the column labels to date format (using .to_datetime()

df = df.set_index(['Company Name', 'ID'])
df.columns = pd.to_datetime(df.columns)

Third, I re-sampled in monthly intervals, using the 'axis=1' to aggregate by column. This creates one month per column. Convert from month-end dates to periods with 'to_period()':

df = df.resample('M', axis=1).sum()
df.columns = df.columns.to_period('M')

                                 2000-01  2000-02
Company Name             ID                      
Reliance Industries Ltd. 100325   104.81     66.0
Tata Consultancy Service 123455   248.00    130.0
jsmart
  • 2,921
  • 1
  • 6
  • 13