1

I have a list of dataframes with these columns

Color Date     Fruit     Num

all have same columns.

I need to re-arrange columns. However, for loop doesn't seem to work.

for i in [df1,df2,df3,df4,df5,df6]:
    i = i[['Date','Fruit','Num','Color']]  

this way

df1 = df1[['Date','Fruit','Num','Color']]

it changes columns order but why not in loop. Isn't i every time looping through each dataframe and assigning reorder of column names.

Any advice?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
rocksailor
  • 21
  • 2

1 Answers1

1

Consider using dictionary of DFs instead of list of DFs:

Given data sets:

In [470]: df1
Out[470]:
    c   b   a
0  63  85  49
1  51  20  43
2  92  67  93
3  58  11  96
4  19  70  82

In [471]: df2
Out[471]:
    b   c   a
0  83  53   0
1  45  23  43
2  49  64  93
3  76  34  38
4  98  78  88

In [472]: dfs = {'df1':df1, 'df2':df2}

Solution:

In [473]: for k in dfs.keys():
     ...:     dfs[k] = dfs[k][['a','b','c']]
     ...:

In [474]: dfs
Out[474]:
{'df1':     a   b   c
 0  49  85  63
 1  43  20  51
 2  93  67  92
 3  96  11  58
 4  82  70  19, 'df2':     a   b   c
 0   0  83  53
 1  43  45  23
 2  93  49  64
 3  38  76  34
 4  88  98  78}

In [475]: dfs['df1']
Out[475]:
    a   b   c
0  49  85  63
1  43  20  51
2  93  67  92
3  96  11  58
4  82  70  19

In [476]: dfs['df2']
Out[476]:
    a   b   c
0   0  83  53
1  43  45  23
2  93  49  64
3  38  76  34
MaxU - stand with Ukraine
  • 205,989
  • 36
  • 386
  • 419