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

Time:05-19

I'm trying to create an Inverted File index to hold TF-IDF for my vocabulary, and I've created a pandas dataframe to hold the data like so:

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

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 these custom rows? am I able to do something like TF_IDF["life","1_1"] to reference row "life" in column "1_1"

(I have tried a few versions of this but none seem to work)

CodePudding user response:

TF_IDF['0']['life'] will get you there

Instead of removing the question, I'll leave it up, just in case someone else also cant find the answer anywhere else online

CodePudding user response:

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
  • Related