Home > Back-end >  Check if and what the name of an index column of a pandas dataframe is?
Check if and what the name of an index column of a pandas dataframe is?

Time:02-22

I have a pandas dataframe and I would like to ask the user to set the index column like so:

indexinput = input("Set index column: (Leave blank for none")

then I pass indexinput into set_index()

In order to check that this worked I would like to print the name of the index column, how can I do this?

Thanks

**** EDIT ****

I have followed advice below and do data.index.name However is has returned none. Could someone problem solve for me?

def load_data():
    is_data_loaded = False
    while is_data_loaded == False:
        rawdatafile = str(input("Please select a file. You may add the csv extention or choose to omit it"))
        data_wo_ext = os.path.splitext(rawdatafile)[0]
        datafile = data_wo_ext   ".csv"
        try:
            data = pd.read_csv(datafile, header = 0)
            data = data.astype(float)
            is_data_loaded = True
        
                
        except Exception as e:
            print(e)
            print("Please try again")
    print(list(data.columns))
    indexinput = input("Set index column: (Leave blank for none")
    if indexinput != "":
        
        try:
            data.set_index(indexinput)
            print(data.index.name)
            return data
        except Exception as e2:
            print(e2)
            print("Please enter an index or leave blank")
        else:
            pass
        
    print("success")
    return data

CodePudding user response:

Use:

df = pd.DataFrame({'date':['03/04/2006', '05/04/2006'], 'name': [10,15]})
indexinput = 'name'

# Be careful here.
df = df.set_index(indexinput)
df.index.name

For demonstration I set the indexinput manually. the result:

enter image description here

  • Related