Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 450
Richard Avatar asked Mar 28 '16 11:03

Richard


People also ask

How do I extract a value from a column in pandas?

You can extract a column of pandas DataFrame based on another value by using the DataFrame. query() method. The query() is used to query the columns of a DataFrame with a boolean expression.

What is ILOC () in python?

The iloc() function in python is one of the functions defined in the Pandas module that helps us to select a specific row or column from the data set. Using the iloc() function in python, we can easily retrieve any particular value from a row or column using index values.

How do you select individual columns in python?

To select a single column, use square brackets [] with the column name of the column of interest.


1 Answers

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
like image 77
jezrael Avatar answered Oct 01 '22 12:10

jezrael