Home > Net >  In python, get inconsistent returns when trying to reverse Pandas DataFrame values
In python, get inconsistent returns when trying to reverse Pandas DataFrame values

Time:09-10

I am trying to reverse values of DataFrame in Python as in the following codes. Strangely, x retuns what expected, but not y.

import pandas as pd
import pandas_datareader as pdr

x = pdr.DataReader('TQQQ', data_source='yahoo', start='2000-01-01')  
y = pdr.DataReader('^NDX', data_source='yahoo', start='2000-01-01') # ^NDX is a symbol for Nasdaq 100 Index

x[:] = x[::-1]
y[:] = y[::-1]

print(x)
print(y)

I suppose which symbol is called should not be a matter, but it seems to be matter.

Please help with it. Thank in advance for any comment and advice.

CodePudding user response:

You should be using these lines instead

x = x[::-1]
y = y[::-1]

Alternatively, you could use sort_values() to reverse the dataframe

x = x.sort_values('Date', ascending=False)
y = y.sort_values('Date', ascending=False)

CodePudding user response:

x[::-1] # reverses the data frame along with index i.e., date
x[:]=x[::-1] # This replaces the data frame values but does not change index.

Hope this helps.

  • Related