How to get a value from a cell of a dataframe?
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 [3]: sub_df
Out[3]:
A B
2 -0.133653 -0.030854
In [4]: sub_df.iloc[0]
Out[4]:
A -0.133653
B -0.030854
Name: 2, dtype: float64
In [5]: sub_df.iloc[0]['A']
Out[5]: -0.13365288513107493
These are fast access for scalars
In [15]: df = pandas.DataFrame(numpy.random.randn(5,3),columns=list('ABC'))
In [16]: df
Out[16]:
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 [17]: df.iat[0,0]
Out[17]: -0.074171888537611502
In [18]: df.at[0,'A']
Out[18]: -0.074171888537611502
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[0]
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 [55]: df1.loc['a', 'A'] Out[55]: 0.13200317033032932
It doesn't need to be complicated:
val = df.loc[df.wd==1, 'col_name'].values[0]