Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
173 views
in Technique[技术] by (71.8m points)

python - How to get scalar value on a cell using conditional indexing

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'>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...