When building date and time index data, place markers on a chart on certain days (for example, weekends)

I create a DataFrame pandas with DatetimeIndex as follows:

import datetime import pandas as pd import numpy as np import matplotlib.pyplot as plt # create datetime index and random data column todays_date = datetime.datetime.now().date() index = pd.date_range(todays_date-datetime.timedelta(10), periods=14, freq='D') data = np.random.randint(1, 10, size=14) columns = ['A'] df = pd.DataFrame(data, index=index, columns=columns) # initialize new weekend column, then set all values to 'yes' where the index corresponds to a weekend day df['weekend'] = 'no' df.loc[(df.index.weekday == 5) | (df.index.weekday == 6), 'weekend'] = 'yes' print(df) 

What gives

  A weekend 2014-10-13 7 no 2014-10-14 6 no 2014-10-15 7 no 2014-10-16 9 no 2014-10-17 4 no 2014-10-18 6 yes 2014-10-19 4 yes 2014-10-20 7 no 2014-10-21 8 no 2014-10-22 8 no 2014-10-23 1 no 2014-10-24 4 no 2014-10-25 3 yes 2014-10-26 8 yes 

I can easily build color A with pandas by doing:

 df.plot() plt.show() 

which displays the row of column A but does not contain the weekend column because it does not contain numeric data.

Plot of 'A' but not of 'weekend'

How can I put a β€œmarker” in every place of column A , where the weekend column is yes ?

+6
source share
1 answer

Meanwhile, as I found out, it is as simple as using boolean indexing in pandas. Plot execution directly using pyplot instead of pandas' own plot wrapper (which is more convenient for me):

 plt.plot(df.index, df.A) plt.plot(df[df.weekend=='yes'].index, df[df.weekend=='yes'].A, 'ro') 

Plot of 'A' with weekend markers

Now red dots mark all weekends given by df.weekend='yes' .

+7
source

Source: https://habr.com/ru/post/977128/


All Articles