Skip to content
Advertisement

How do I name the dataframe index after a variable result?

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

Advertisement

Answer

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 yours:

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)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement