Home > Software design >  How do I name the dataframe index after a variable result?
How do I name the dataframe index after a variable result?

Time:04-20

I have a variable called 'Specimen' from a dataframe imported from a xlsx file, and I want to implement the result of this variable (in this case 25) in a new dataframe?

What I have:

Specimen          = np.array(df.loc['Specimen', ['x1']])
Specimen

array([[25.0]], dtype=object)

New_Df = pd.DataFrame(Variable_list)   
New_Df['Result_list'] = Result_list
New_Df.columns =['Name', 'Result']
New_Df
    Name         Result
0   L_TotalNOT  52.541091
1   R_TotalNOT  40.139543
2   L_TotalGON  59.271545
3   R_TotalGON  63.784038

What I want:

25  Name         Result
0   L_TotalNOT  52.541091
1   R_TotalNOT  40.139543
2   L_TotalGON  59.271545
3   R_TotalGON  63.784038

I have tried

Output.index.names = [Specimen]

But this gives the following error: TypeError: RangeIndex.name must be a hashable type

ps: I'm quite new here, so I hope I'm asking thing the right way, Many thanks in advance

CodePudding user response:

I feel like I may be missing a requirement from your question but here is what I think might work for you:

Set the variable to match your's:

Specimen = np.array([[25.0]], dtype=object)
Specimen

array([[25.0]], dtype=object)

Specimen[0][0]
25.0

Then rename the index:

new_df.index.rename(Specimen[0][0], inplace=True)

            Name     Result
25.0                       
0     L_TotalNOT  52.541091
1     R_TotalNOT  40.139543
2     L_TotalGON  59.271545
3     R_TotalGON  63.784038

The index has been renamed:

new_df.index
Int64Index([0, 1, 2, 3], dtype='int64', name=25.0)

CodePudding user response:

I think you're looking for pd.DataFrame.rename_axis

pd.DataFrame({
    'a' : [1,2,3,4],
    'b' : [5,6,7,8]
}).rename_axis(25)

    a   b
25      
0   1   5
1   2   6
2   3   7
3   4   8
  • Related