Home > Net >  doing same operation on multiple variables using pandas
doing same operation on multiple variables using pandas

Time:11-23

I am new to python and am working with 18 pandas dataframes at once. I want to do the same operation on all the dataframes but havent seemed to find a one line bit of code to do it for me. I get what I want but I do individual lines of code for all 18 variables just now.

example

    a = [1,3; 2,1; 3,4]
    b = [1,6; 2,9; 3,2]
    c = [1,5; 2,8; 3,9]

I want to create a 3rd column in all these variables, which is column 2 multiplied by lets say 4. What would be the most efficient way to write a code to do the same operation for all the variables at once so that my outputs has variables a,b,c with 3 columns, with the third being column 2 x 4

CodePudding user response:

Your question is a bit unclear - you already have 3 columns listed and you shouldn't be using semicolons in your list (syntax errors).

Much to what another user said: Put all of your dataframes names in a list and then write a quick for loop to do that. As a brief example:

df_list = ['df1','df2',....'dfn']

for i in df_list:
    globals()[i][2] = globals()[i].iloc[1]*4

This should iterate through your list of dataframes, multiplying the 2nd column by the number 4, and then storing it your third column (overwriting what was there before).

CodePudding user response:

Just use a simple loop and do your thing for each dataframe:

for df in [df1, df2, df3, df4, df5, ...]:
    # do your thing with df, e.g.:
    print(df)
  • Related