Search code examples
pythonpandasdataframenlptf-idf

How to access a row in a pandas dataframe with custom index labels?


I've created a pandas dataframe to hold the data like so:

TF_IDF = pd.DataFrame(index = vocab)
TF_IDF['0'] = 0

where vocab is an array of strings, so the index label of each column is the corresponding string

so when I print it, it looks like this:

           0
life       0
math       0
student    0
experi     0
control    0
...       ..
slave      0
linga      0
31-32      0
democrat   0
unsustain  0

How would I access a row at a given index by using a string?

for example, if I have the string "math" how would one access the value using the index label "math"?


Solution

  • You should use .loc[] rather than chained indexing (as in your answer) as it's more efficient, and chained indexing can sometimes raise a SettingWithCopy warning (read more here).

    To use .loc, you would call it like below:

    df.loc[row_index(es), col_names]
    

    Which would be the below in your example:

    TF_IDF.loc['life', '0']
    

    returns:

    0