Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python dataframe: Finding a value in same row as a defined value in a different column

I have a large Pandas dataframe:

    Time      P     T   R   H  
00000.0 1004.6  12.2  96    12  
00001.0 1004.2  12.1  96    15  
00002.0 1003.5  11.9  96    21  
00003.0 1002.8  12.0  96    27  
00004.0 1002.0  12.1  96    34  
00005.0 1001.4  12.1  96    39  
00006.0 1000.3  12.2  96    48

00007.0  999.5  12.1  96    55  
00008.0  998.9  12.2  96    59  
00009.0  998.0  12.1  96    67  
00010.0  997.3  13.1  96    73  
00011.0  996.9  13.2  97    76 

00013.0  995.3  13.3  97    90  
00014.0  994.6  13.6  97    96  
00015.0  994.3  13.5  97    98  
00016.0  993.6  13.5  96   104  
00017.0  992.5  13.3  96   114  
00018.0  991.8  13.3  96   119  
00019.0  991.7  13.7  97   120  

I want to find the value in a row when a value in another column (same row) has a defined value. For example, I want to write a code that find what the "T" value is in same row where the "P" value is 1002.8.

like image 237
Jonathon Avatar asked Apr 09 '18 17:04

Jonathon


People also ask

How do I get the value of a column based on another column value?

You can extract a column of pandas DataFrame based on another value by using the DataFrame. query() method. The query() is used to query the columns of a DataFrame with a boolean expression.

How do you get a particular column value from a DataFrame in Python?

You can use the loc and iloc functions to access columns in a Pandas DataFrame. Let's see how. If we wanted to access a certain column in our DataFrame, for example the Grades column, we could simply use the loc function and specify the name of the column in order to retrieve it.


2 Answers

IIUC, use boolean indexing:

df.loc[df.P == 1002.8, 'T']

Output:

3    12.0
Name: T, dtype: float64

Or to get that value use:

df.loc[df.P == 1002.8, 'T'].values[0]

Output

12.0
like image 107
Scott Boston Avatar answered Oct 23 '22 12:10

Scott Boston


df['T'].where(df['P'] == 1002.8)

will give you a Series with NaN where the condition is False and the value of T where it is True.

df['T'].where(df['P'] == 1002.8).dropna()

will give you a Series with just the values where the condition is met.

If it is the case, as you say, that this will only happen one time, then

df['T'].where(df['P'] == 1002.8).dropna().values[0]

will give you just that value.

like image 24
Silenced Temporarily Avatar answered Oct 23 '22 11:10

Silenced Temporarily