2

何よりもまず、私は Python の専門家ではなく、まだ pandas の使い方を学んでいることを正確に伝えたいと思います。古い投稿を掘り下げますが、適切な答えが見つかりません。

私は 92 の契約のデータ分析をコーディングしようとしています。それぞれについて、特定の分析 (毎回同じデータフレームのいくつかの列を取得) をプロットし、各分析を別のフォルダー (分析 1、分析 2、...) に保存したいと思います。

これまで、多くの困難に直面してきました。したがって、何をプロットするかに焦点を当てる前に、各プロットの保存を毎回異なる .png ファイルにコーディングする方法を理解したいと思います。私が試したコードは、フォルダーに移動したときに何も保存されていないようです。

waykiki の助けのおかげで、コードを更新することができました。これで、生成する分析と同じ数のフォルダーを作成する方法がわかりました。それでも、分析ごとに 92 個のグラフのプロットをコーディングする方法を理解していないようです。私のコードは次のようになります。

import pandas as pd
import matplotlib.pyplot as plt
import os

# Folder in which I want the analyses to be saved
URL5 = r"C:\Users\A\AppData\Local\Programs\Python\Python39"
# 1 graph per ID_Contrat (thus, 92 graphs)
groups = outer_merged_df.groupby("ID_Contrat") #where outer_merged_df is my dataframe
# How to name each plot.
List_ID_Contrat = outer_merged_df["ID_Contrat"].tolist()

def create_plot(file_name, x, y):
    # Create your plot. It is my understanding that here I should just give the x and the y I want to plot.
    fig = plt.figure()
    plt.plot(x, y, color = "red", kind = "line", legend = "true", linewidth = 2)
    plt.savefig(file_name)
    plt.show()

def main():
    # must be full-path. 
    parent_folder = URL5
    # move to parent directory
    os.chdir(parent_folder)
    # I want file_name to be different for each graph
    extension = ".png"
    # 5 = how many analyses I want to do
    for i in range(5):
        for name in List_ID_Contrat :
            file_name = "Analyse" + str[i+1] "{}" + extension.format(name) # I want file_name to be different for each graph and looking like "Analyse i Contrat XX"
        # Create a new folder
        folder_name = 'Analysis ' + str(i+1)
        os.mkdir(folder_name)
        full_file_name = folder_name + '/' + file_name
        x = np.linspace(1,100,100)
        y = np.random.random(100)
        create_plot(full_file_name, x, y)
        print("plot "+ savefile +" finished".format(name))
        
if __name__ == "__main__":
    main()

それでも、コードを実行すると、92 個のグラフをプロットしたり、フォルダーを作成したりしなくなります (Waykiki の方法を使用していましたが)。最初のラウンドで for ループが壊れています (フォルダー "Analysis 1" のみを取得します)。次のエラー メッセージが表示されます。

AttributeError: 'Line2D' object has no property 'kind'

グラフを保存する方法を教えてください。私は道に迷っています..

ありがとう

4

3 に答える 3