Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Check if and what the name of an index column of a pandas dataframe is?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading