How to get a value from a cell of a dataframe?
I have constructed a condition that extract exactly one row from my data frame:
d2 = df[(df['l_ext']==l_ext) & (df['item']==item) & (df['wn']==wn) & (df['wd']==1)]
Now I would like to take a value from a particular column:
val = d2['col_name']
But as a result I get a data frame that contains one row and one column (i.e. one cell). It is not what I need. I need one value (one float number). How can I do it in pandas?
If you have a DataFrame with only one row, then access the first (only) row as a Series using
iloc, and then the value using the column name:
In : sub_df Out: A B 2 -0.133653 -0.030854 In : sub_df.iloc Out: A -0.133653 B -0.030854 Name: 2, dtype: float64 In : sub_df.iloc['A'] Out: -0.13365288513107493
These are fast access for scalars
In : df = pandas.DataFrame(numpy.random.randn(5,3),columns=list('ABC')) In : df Out: A B C 0 -0.074172 -0.090626 0.038272 1 -0.128545 0.762088 -0.714816 2 0.201498 -0.734963 0.558397 3 1.563307 -1.186415 0.848246 4 0.205171 0.962514 0.037709 In : df.iat[0,0] Out: -0.074171888537611502 In : df.at[0,'A'] Out: -0.074171888537611502
Read more... Read less...
You can turn your 1x1 dataframe into a numpy array, then access the first and only value of that array:
val = d2['col_name'].values
Most answers are using
iloc which is good for selection by position.
If you need selection-by-label
loc would be more convenient.
For getting a value explicitly (equiv to deprecated df.get_value('a','A'))
# this is also equivalent to df1.at['a','A'] In : df1.loc['a', 'A'] Out: 0.13200317033032932
I needed the value of one cell, selected by column and index names. This solution worked for me:
It looks like changes after pandas 10.1/13.1
I upgraded from 10.1 to 13.1, before iloc is not available.
Now with 13.1,
iloc['label'] gets a single value array rather than a scalar.
date 2014-02-26 118.2 name:Close, dtype: float64
The quickest/easiest options I have found are the following. 501 represents the row index.