Print the raw value of a column alone, in pandas?

I have a dataframe:

df = pd.DataFrame([ { 'name': 'george', 'age': 23 }, {'name': 'anna', 'age': 26}])

Now I want to retrive George’s age:

df[df.name == 'george'].age

But this outputs some extra information along with the raw value:

0    23
Name: age, dtype: int64

How do I just get it to print 23?

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

You can use loc + values for converting Serie to numpy array and then select first value by [0]:

print (df.loc[df.name == 'george', 'age'].values)
[23]
print (df.loc[df.name == 'george', 'age'].values[0])
23

Or simply select first value of Series with iloc:

print (df.loc[df.name == 'george', 'age'].iloc[0])
23

Or select first item by iat:

print (df.loc[df.name == 'george', 'age'].iat[0])
23

Or use Series.item:

print (df.loc[df.name == 'george', 'age'].item())
23

If possible no match value, above solutions failed.

Then is possible use next with iter trick:

print (next(iter(df.loc[df.name == 'george', 'age']),'no match value'))
23

print (next(iter(df.loc[df.name == 'jano z hornej dolnej', 'age']),'no match value'))
no match value

Method 2

Might as well make my comment an answer:

df[df.name == 'george'].age.values[0]

or

int(df[df.name == 'george'].age)

should work

Method 3

df = [ { 'name': 'george', 'age': 23 }, {'name': 'anna', 'age': 26}]
k = [x['age'] for x in df if x['name'] == 'george']
print k


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x