有没有办法在python中优化这段代码的子情节?

mpgws1up  于 2023-01-19  发布在  Python
关注(0)|答案(1)|浏览(114)

我写了一段代码,在按月汇总的数据中为每年的净值创建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()
jdgnovmf

jdgnovmf1#

您可以循环通过.groupby("YEAR")
下面是一些例子:

df = pd.DataFrame({
    "YEAR": ["2022", "2022", "2023", "2023"],
    "x":[1, 2, 3, 4],
    "y": [1, 2, 3, 4]
})

for i, (year, gr) in enumerate(df.groupby("YEAR")):
    plt.subplot(1, 2, i+1)
    plt.plot(gr["x"], gr["y"])

相关问题