Home > Net >  Change index of multiple dataframes at once
Change index of multiple dataframes at once

Time:03-15

Here is my earlier part of the code - 
import pandas as pd
import itertools as it
import numpy as np

a= pd.read_excel(r'D:\Ph.D. IEE\IEE 6570 - IR Dr. Greene\3machinediverging.xlsx')
question = pd.DataFrame(a).set_index('Job')
df2 = question.index
permutations = list(it.permutations(question.index))

dfper = pd.DataFrame(permutations)
for i in range(len(dfper)):
    fr = dfper.iloc[0:len(dfper)]
fr.index.name = ''
print(fr)

for i in range(0, fr.shape[0], 1):
    print (fr.iloc[i:i 1].T)

This gives me 120 dataframes.

    0
0   A

1   B

2   C

3   D

4   E


    1
0   A

1   B

2   C

3   E

4   D

and so on...

I would like to change the index of these dataframes to the alphabet column (using a for loop). Any help would be really appreciated. Thank you.

CodePudding user response:

import pandas as pd

df1 = pd.DataFrame({0: [ 'A', 'B', 'C', 'D', 'E']})
df2 = pd.DataFrame({1:  [ 'A', 'B', 'C', 'D', 'E']})

df_list =  [df1, df2]

for df in df_list:
    # set the first column as index
    df.set_index(df.columns[0], inplace=True)

CodePudding user response:

I would organize all dataframes in a list:

df_list = [df1, df2, df3,...]

and then:

for df in df_list: df = df.set_index(df.columns[0])
  • Related