Home>

With DataFrame.set.index (),
After changing the index to any column name,
Cannot extract value by row name.

(In the example below,
I want to extract the value of Iwate prefecture after set.index ())

Please take appropriate measures.

import pandas as pd
# Download files from Cabinet Office database (http://wwwb.cao.go.jp/ittaikaikaku/mDownload/index.php)
df = pd.read_csv ('Real debt service ratio.csv', encoding = 'shift_jis')
#Delete rows and columns with missing values ​​from the read file
df = df.dropna (how = 'all', axis = 0) .dropna (how = 'all', axis = 1)
df.head ()


  

# Delete the Unnamed: 0 in the first column
df = df.drop ([df.columns [0]], axis = 1)
#Unnamed: 1 in the 2nd column changed to prefecture
df = df.rename (columns = {df.columns [0]: 'states'})
df.head ()


  

# Extract the value of Iwate prefecture
df.iloc [2]


  

◎ Here is the main subject.

Change # column index to state
df = df.set_index ('prefecture')
df.head ()


  

df.loc ['Iwate']


KeyError: 'Iwate Prefecture'


◎ Addition

Reference in response to Ben @ jeanbiego's answer

df.index


  

df.index.str.strip ()


  

  • Answer # 1

    There may be blank spaces to the left and right of "Iwate Prefecture".
    Please try the following.

    df.index = df.index.str.strip () # strip blanks
    df.loc ['Iwate']

Related articles