Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get scalar value on a cell using conditional indexing

Tags:

python

pandas

I have the dataframe shown below. I need to get the scalar value of column B, dependent on the value of A (which is a variable in my script). I'm trying the loc() function but it returns a Series instead of a scalar value. How do I get the scalar value()?

>>> x = pd.DataFrame({'A' : [0,1,2], 'B' : [4,5,6]}) >>> x    A  B 0  0  4 1  1  5 2  2  6  >>> x.loc[x['A'] == 2]['B'] 2    6 Name: B, dtype: int64  >>> type(x.loc[x['A'] == 2]['B']) <class 'pandas.core.series.Series'> 
like image 366
user4979733 Avatar asked Jun 12 '15 22:06

user4979733


People also ask

How do you set the value of a cell in a DF?

You can set cell value of pandas dataframe using df.at[row_label, column_label] = 'Cell Value'. It is the fastest method to set the value of the cell of the pandas dataframe. Dataframe at property of the dataframe allows you to access the single value of the row/column pair using the row and column labels.

How do I get pandas series value?

Example #1: Use Series. get() function to get the value for the passed index label in the given series object. Output : Now we will use Series.

How do I get the index of DF Loc?

loc[] to find Row index which column match value. The pandas dataframe. loc method is used to access the row and column by index(label) and column name that is passed by the column label(Marks) to df. loc[df['Marks'] = 100 and it will return the rows which satisfy the given condition.


2 Answers

First of all, you're better off accessing both the row and column indices from the .loc:

x.loc[x['A'] == 2, 'B'] 

Second, you can always get at the underlying numpy matrix using .values on a series or dataframe:

In : x.loc[x['A'] == 2, 'B'].values[0] Out: 6 

Finally, if you're not interested in the original question's "conditional indexing", there are also specific accessors designed to get a single scalar value from a DataFrame: dataframe.at[index, column] or dataframe.iat[i, j] (these are similar to .loc[] and .iloc[] but designed for quick access to a single value).

like image 177
Noah Avatar answered Sep 29 '22 00:09

Noah


elaborating on @ShineZhang comment:

x.set_index('A').at[2, 'B']

6

pd.__version__

u'0.22.0'

like image 23
ihadanny Avatar answered Sep 29 '22 00:09

ihadanny