Jonathon
Jonathon

Reputation: 271

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.

Upvotes: 8

Views: 16086

Answers (2)

Silenced Temporarily
Silenced Temporarily

Reputation: 1004

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.

Upvotes: 1

Scott Boston
Scott Boston

Reputation: 153550

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

Upvotes: 11

Related Questions