Python Forum
How to create a column with periodic entries? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to create a column with periodic entries? (/thread-31527.html)



How to create a column with periodic entries? - Mark17 - Dec-16-2020

I'm trying to create a stock chart but with date on the x-axis, it's a black blur because the dataframe has 3407 entries.

So... what I'm thinking of doing is creating a new df column that has entries every n rows to allow it to be seen.

I tried this:
ES_skel = ES.drop(['Open','High','Low','Vol'],axis=1)
ES_skel.index = ES_skel["Date"].apply(lambda x: pd.Timestamp(x))

for i in range(len(ES_skel)):
    if i%5 == 0:
        ES_skel["Month_Year"] = ES_skel.Date #ES_skel.index.strftime('%Y-%m')

print(ES_skel.head(15))
This resulted in the new Month_Year column being populated with the date for every row. Adding this else clause:
    else: ES_skel["Month_Year"] = None   
resulted in None for every row in the new Month_Year column.

What happened? With the if condition being executed initially, why was the else condition executed when included? And why was execution done every row rather than every 5th row per the i%5 line?

Thanks!


RE: How to create a column with periodic entries? - Mark17 - Dec-16-2020

I think I know why this happened: whether or not i%5==0, the respective condition was executed for all cells in the column. Right? If I included the else clause and range(len(ES_skel)) led to the else clause being executed, then all cells in the column would show None.

This might also explain why the program took so long to run: for each i, it was writing and overwriting 3407 entries?

What I somehow need to do is call just the particular cell... maybe with .iloc[i] somewhere?


RE: How to create a column with periodic entries? - Mark17 - Dec-16-2020

This works:
ES_skel["Month_Year"]=np.nan
for i in range(len(ES_skel)):
    if i % 5 == 0:
        ES_skel.iloc[i,2] = ES_skel.iloc[i,0] 
My actual problem, however, seemed to be:
ax.plot(ES_skel['Month_Year'], ES_skel['Close']); plt.show()
I deleted the first argument to let matplotlib automatically choose logical and readable spacing of the axis labels.