我有一个 pandas 数据框(存储在 Excel 中),其中包含某些组的时间序列。 我想为这些组绘制时间序列的线图。我无法理解 pyplot 中的屏蔽图。我需要在冬季掩盖这些图(图中的间隙)。
我的起点是这里的页面: https://matplotlib.org/gallery/lines_bars_and_markers/masked_demo.html
我看到了 pandas mask 和 where 函数的文档。 我还看到了 numpy.ma.masked_where 函数文档。
我可以使用 pandas.mask 函数 - 但只能用于一列。我无法找到使用 ['Months'] 列来屏蔽我的 ['Values'] 列的方法。
我尝试使用 pandas.as_matrix() 将两列导出到 numpy。然后我使用 numpy.ma.masked_where 屏蔽了 ['Values']。然而,当我尝试将其放回 pandas 数据帧时,它被取消屏蔽,并且值仍然存在。
#Lets say I have a dataframe called df.
#It has following columns [['Date','Month', 'Values', 'GroupName']]
#This works, and the values seem to be masked, because they print as --
months = df['Month'].as_matrix()
values = df['Values'].as_matrix()
masked = np.ma.masked_where(months in ['5','6','7','8','9'], values)
#However this here unmasks the values =(
df['MaskedValues'] = masked
#This is how I do the plotting - I plot values from each group onto one plot
fig, ax = plt.subplots()
#Loops over groups and adds them to the plot
for key, group in df.groupby(['GroupName']):
ax = group.plot(ax=ax, kind='line', x='Date', y='MaskedValues', label=key, figsize=(40,15), fontsize=30, color='black')
我的最终目标是获得一个线图,其中夏季月份以外的线被删除。我希望情节中有一个间隙。
最佳答案
我认为你的情况需要
fig, ax = plt.subplots(figsize=(40, 15))
w = (10, 11, 12, 1, 2, 3, 4)
for key, group in df.groupby(['GroupName']):
group.mask(df.Month.isin(w)).plot(ax=ax, x='Date', y='Values', label=key, fontsize=30, color='black')
请注意,您不需要每次迭代都分配 ax,并且应该将Figsize 放入子图中。
<小时/>我在这里给你一个 mcve,这是两年内的一些正弦数据:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
t = pd.date_range('1.1.2000', '31.12.2001')
data = np.sin(np.arange(len(t.day))/10)
在相应的数据框中,添加了一个附加列month
,该列将用于屏蔽:
df = pd.DataFrame({'value': data, 'month': t.month}, index=t)
(在我的示例中,冬天在三月后就结束了......:))
w = (10, 11, 12, 1, 2, 3)
然后,您可以绘制除 month
位于 w
中的值之外的所有值:
df.value.mask(df.month.isin(w)).plot()
plt.show()
关于python - 如何根据另一列的值屏蔽 pandas 列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56101749/