HiveBrain v1.2.0
Get Started
← Back to all entries
snippetpythonCritical

How can I get a value from a cell of a dataframe?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
cellhowvaluegetcandataframefrom

Problem

I have constructed a condition that extracts exactly one row from my dataframe:
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 dataframe 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?

Solution

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

Code Snippets

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

Context

Stack Overflow Q#16729574, score: 840

Revisions (0)

No revisions yet.