我写了一段代码,在按月汇总的数据中为每年的净值创建8个子图。我尝试使用两个for循环优化代码,但我不知道如何将查询部分捆绑在pd df中。有没有办法以更好的方式重写它或优化这段长代码?
VF_data只是一个Pandas Dataframe ,其中包含每年每个月聚合的数值正值和负值。其他列是月、年、日期。
提前感谢你们!!
def plot_MTY(df, aggregate_col='NET'):
plt.subplot(2, 4, 1)
VF_data=df.query("(YEAR == '2015')")
aggregated_target = aggregate_data(VF_data, 'DATES', aggregate_col)
plt.plot(aggregated_target, label = 'df', linestyle="-")
plt.axhline(y=0, color='b', linestyle='-')
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.subplot(2, 4, 2)
VF_data=df.query("(YEAR == '2016')")
aggregated_target = aggregate_data(VF_data, 'DATES', aggregate_col)
plt.plot(aggregated_target, label = 'df', linestyle="-")
plt.axhline(y=0, color='b', linestyle='-')
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.subplot(2, 4, 3)
VF_data=df.query("(YEAR == '2017')")
aggregated_target = aggregate_data(VF_data, 'DATES', aggregate_col)
plt.plot(aggregated_target, label = 'df', linestyle="-")
plt.axhline(y=0, color='b', linestyle='-')
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.subplot(2, 4, 4)
VF_data=df.query("(YEAR == '2018')")
aggregated_target = aggregate_data(VF_data, 'DATES', aggregate_col)
plt.plot(aggregated_target, label = 'df', linestyle="-")
plt.axhline(y=0, color='b', linestyle='-')
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.subplot(2, 4, 5)
VF_data=df.query("(YEAR == '2019')")
aggregated_target = aggregate_data(VF_data, 'DATES', aggregate_col)
plt.plot(aggregated_target, label = 'df', linestyle="-")
plt.axhline(y=0, color='b', linestyle='-')
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.subplot(2, 4, 6)
VF_data=df.query("(YEAR == '2020')")
aggregated_target = aggregate_data(VF_data, 'DATES', aggregate_col)
plt.plot(aggregated_target, label = 'df', linestyle="-")
plt.axhline(y=0, color='b', linestyle='-')
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.subplot(2, 4, 7)
VF_data=df.query("(YEAR == '2021')")
aggregated_target = aggregate_data(VF_data, 'DATES', aggregate_col)
plt.plot(aggregated_target, label = 'df', linestyle="-")
plt.axhline(y=0, color='b', linestyle='-')
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.subplot(2, 4, 8)
VF_data=df.query("(YEAR == '2022')")
aggregated_target = aggregate_data(VF_data, 'DATES', aggregate_col)
plt.plot(aggregated_target, label = 'df', linestyle="-")
plt.axhline(y=0, color='b', linestyle='-')
locs, labels = plt.xticks()
plt.setp(labels, rotation=90)
plt.gcf().set_size_inches(15, 8)
plt.show()
1条答案
按热度按时间jdgnovmf1#
您可以循环通过
.groupby("YEAR")
下面是一些例子: