Question
Asked By – Eduardo
Say I have the following DataFrame
Letter Number A 1 B 2 C 3 D 4
Which can be obtained through the following code
import pandas as pd
letters = pd.Series(('A', 'B', 'C', 'D'))
numbers = pd.Series((1, 2, 3, 4))
keys = ('Letters', 'Numbers')
df = pd.concat((letters, numbers), axis=1, keys=keys)
Now I want to get the value C from the column Letters.
The command line
df[df.Letters=='C'].Letters
will return
2 C Name: Letters, dtype: object
How can I get only the value C and not the whole two line output?
Now we will see solution for issue: How to get a value from a Pandas DataFrame and not the index and object type
Answer
df[df.Letters=='C'].Letters.item()
This returns the first element in the Index/Series returned from that selection. In this case, the value is always the first element.
EDIT:
Or you can run a loc() and access the first element that way. This was shorter and is the way I have implemented it in the past.
This question is answered By – valkn0t
This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0