2

I am new to Python and struggle with a seemingly simple problem. I am trying to change the format of the DateTimeIndex to show only years and months. I am still returned the original format (YYYY-MM-DD). Thank you in advance.

from numpy import array
import pandas as pd
import quandl
import numpy as np
import matplotlib.pyplot as plt

new_orders=quandl.get("ISM/MAN_NEWORDERS.5")
df = quandl.get("USTREASURY/YIELD", collapse="monthly")

#plt.plot(new_orders[4])
#plt.show()

df2=pd.DataFrame(df['10 YR'])

df2.index.strftime('%Y-%m')

print(df2.index)
Huw Thomas
  • 317
  • 1
  • 8
PRA
  • 29
  • 2

2 Answers2

0

You need to take the index values, format them appropriately and then set these formatted values as the new index, like so:

from numpy import array
import pandas as pd
import quandl
import numpy as np
import matplotlib.pyplot as plt

new_orders=quandl.get("ISM/MAN_NEWORDERS.5")
df = quandl.get("USTREASURY/YIELD", collapse="monthly")

df2=pd.DataFrame(df['10 YR'])

dates = df2.index
datesFormatted = dates.strftime('%Y-%m')
df2 = df2.set_index(datesFormatted)

print(df2.index)
Huw Thomas
  • 317
  • 1
  • 8
0

You can change index of DataFrame in place (without creating new object of DataFrame class) using this approach:

df2.index = df2.index.strftime('%Y-%m')

or this one:

df2.set_index(df2.index.strftime('%Y-%m'), inplace=True)
Eduard Ilyasov
  • 3,268
  • 2
  • 20
  • 18