Azi
Azi

Reputation: 11

How to conduct iterative steps with multiple data frames in python ?

I collected some data in the lab and it is stored in multiple excel sheets. I loaded the excel sheets into data frames and now I want to perform the same function for each data frame but i am not sure how.

df = pd.read_csv("TRSCE_5_1.csv")
df1 = pd.read_csv("TRSCE_5_2.csv")

def Function_plot() :  
    X = df[["Frequency(Hz)"]].values
    y = df[" R(Ohm)-data"].values
    y1 = df[" X(Ohm)-data"].values
    plt.title("Resistance vs. Frequency")
    plt.plot(X, y, label = 'Resistance')
    plt.plot(X, y1, label= 'Reactance')
    plt.ylabel('ylabel')
    plt.xlabel('xlabel')
    plt.legend()

    plt.xlabel("Frequency", size=20)
    plt.ylabel("Resistance", size=20)
for each df in [df,df1,df2...,df8]
    Function_plot(df)      

Upvotes: 1

Views: 59

Answers (1)

KRKirov
KRKirov

Reputation: 4004

You can try the code below:

    import glob

    pattern = 'TRSCE*.csv'

    csv_files = glob.glob(pattern)

    df_list = []

    for csv in csv_files:
        df = pd.read_csv(csv)

        # Fill the data frame list
        df_list.append(df)

        # Plot the data frame using your user defined function
        Function_plot(df)

Note that in the last line above your user function is modified to accept a single data frame argument. So the signature of your function needs to change to:

    def Function_plot(df)
        # then the function body

I noticed that the syntax of your for loop in your code has a mistake. If you want to plot in a separate loop then use:

    for each in df_list:
        Function_plot(each)

Upvotes: 1

Related Questions