Home > Software engineering >  Indexing by row name
Indexing by row name

Time:03-03

Can someone please help me with this. I want to call rows by name, so I used set_index on the 1st column in the dataframe to index the rows by name instead of using integers for indexing.

# Set 'Name' column as index on a Dataframe
df1 = df1.set_index("Name", inplace = True)
df1

Output:

AttributeError: 'NoneType' object has no attribute 'set_index'

Then I run the following code:

result = df1.loc["ABC4"]
result

Output:

AttributeError: 'NoneType' object has no attribute 'loc'

I don't usually run a second code that depends on the 1st before fixing the error, but originally I run them together in one Jupyter notebook cell. Now I see that the two code cells have problems.

Please let me know where I went wrong. Thank you!

CodePudding user response:

Maybe you should define your dataframe?

import pandas as pd
df1 = pd.DataFrame("here's your dataframe")
df1.set_index("Name")

or just

import pandas as pd
df1 = pd.DataFrame("here's your dataframe").set_index("Name")
df1

CodePudding user response:

Your variable "df1" is not defined anywhere before doing something with it. Try this:

# Set 'Name' column as index on a Dataframe
df1 = ''
df1 = df1.set_index("Name", inplace = True)

If its defined before, its value is NONE. So check this variable first. The rest of the code "SHOULD" work afterwards.

CodePudding user response:

use the set_index function for a dataframe

  • Related