Baba_Voss
Baba_Voss

Reputation: 21

Fetching column values in Panda DataFrame using while loop

I have created a panda DataFrame with columns as: "Radius", "Zenith", "Tem". Now I want to retrieve all the temperature values based on the zenith values in the DataFrame. Next thing is to fetch the max and min value of "Tem" for each value of the zenith angle.

I have written the below code block but it is throwing me ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

theta = np.around(np.arange(0,90,90/151),6)
a = np.ndarray(shape=(1,2), dtype=float, order='C')

for i in theta:
    while (final_data[final_data['zenith'] == i]):
        T = final_data[['Tem']].values
        T_max = np.max(T)
        T_min = np.min(T)
        T_range = np.row_stack((a,[[T_max,T_min]])) 

Upvotes: 1

Views: 90

Answers (2)

kait
kait

Reputation: 1357

You could use this to get the min, max, and range

import pandas as pd

df = pd.DataFrame({'Zenith': [70, 70, 70, 80, 80, 80],
                   'Tem':    [20, 21, 22, 23, 24, 25]})

df.groupby('Zenith')['Tem'].agg([
    ('T_min',  'min'),
    ('T_max',  'max'),
    ('T_range', lambda x: x.max() - x.min())
])

Returns

        T_min  T_max  T_range
Zenith
70         20     22        2
80         23     25        2

Upvotes: 1

Arne
Arne

Reputation: 10545

These kinds of operations are already implemented in pandas:

import pandas as pd

# example data
df = pd.DataFrame({'Zenith': [70, 70, 70, 80, 80, 80], 
                   'Tem':    [20, 21, 22, 23, 24, 25]})

# get all temperatures for a given zenith value (e.g. 80)
df.Tem[df.Zenith == 80]
3    23
4    24
5    25
Name: Tem, dtype: int64
# get the minimum temperature for each zenith value
df.groupby('Zenith').min()
       Tem
Zenith  
70     20
80     23
# get the maximum temperature for each zenith value
df.groupby('Zenith').max()
       Tem
Zenith  
70     22
80     25

Upvotes: 1

Related Questions