'Indexing by row name

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!



Solution 1:[1]

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

Solution 2:[2]

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.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 vovakirdan
Solution 2