'Pandas: Grabbing a specific column after filtering dataframe?

How can I get rid of the ratio line of code?

totalCharges_male = df[(df['SeniorCitizen'] == 1) & (df['gender'] == 'Male')]
totalCharges_female = df[(df['SeniorCitizen'] == 1) & (df['gender'] == 'Female')]
ratio = totalCharges_male['TotalCharges'].mean() / totalCharges_female['TotalCharges'].mean() 

print(ratio)


Solution 1:[1]

You may use the loc method. With it you filter and select columns.

meanCharges_male = df.loc[
    (df['SeniorCitizen'] == 1) & (df['gender'] == 'Male'), 
    'TotalCharges'].mean()

meanCharges_female = df.loc[
    (df['SeniorCitizen'] == 1) & (df['gender'] == 'Female'), 
    'TotalCharges'].mean()

ratio = meanCharges_male / meanCharges_female

print(ratio)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Aislan