Dir*_*irk 6 python matplotlib pandas
我使用DatetimeIndex创建一个pandas数据帧,如下所示:
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)
Run Code Online (Sandbox Code Playgroud)
这使
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
Run Code Online (Sandbox Code Playgroud)
我可以通过以下方式轻松地A用大熊猫绘制柱子:
df.plot()
plt.show()
Run Code Online (Sandbox Code Playgroud)
它绘制了一A列的一行,但weekend由于它没有数字数据而遗漏了该列.

如何A在weekend列具有值的列的每个点上放置"标记" yes?
同时我发现,它就像在pandas中使用布尔索引一样简单.直接使用pyplot而不是pandas自己的绘图包装(这对我来说更方便):
plt.plot(df.index, df.A)
plt.plot(df[df.weekend=='yes'].index, df[df.weekend=='yes'].A, 'ro')
Run Code Online (Sandbox Code Playgroud)

现在,红点标记所有周末天数,由df.weekend='yes'值给出.
| 归档时间: |
|
| 查看次数: |
1203 次 |
| 最近记录: |