Hello. I continue to study pandas and encountered the following problem: I have a csv file in which there are n number of columns (well, the values ​​in these columns). There is a column (sign) race - it indicates the nationality of a person. there is a sex column β€” it contains a gender (Male is a man; Female is a woman) and there is a age column β€” age. The task is as follows: to get the maximum age of men of the Amer-Indian-Eskimo race. Just getting the maximum age for both men and women is not a problem:

print(df[df['race'] == 'Amer-Indian-Eskimo'] ['age'].max()) 

In general, I can not calculate the maximum age of men. I do not understand how to specify in the code that the Male value from the sex column should be considered

2 answers 2

Here is another solution that looks a bit more readable:

Data:

 In [7]: df Out[7]: race sex age 0 am 11 1 af 23 2 af 45 3 bm 56 4 bf 39 5 cf 66 

Decision:

 In [9]: df.query("race=='a' and sex=='f'")['age'].max() Out[9]: 45 

UPDATE:

 In [52]: df = pd.read_csv(r'C:\download\adult.data.csv') In [53]: df.query("race=='Amer-Indian-Eskimo' and sex=='Male'")['age'].max() Out[53]: 82 
  • Yes indeed better. Thank you very much! - IT-KOT
  • I gave this error here: expr must be evaluated, <class 'bool'> given. The age column has int64 - IT-KOT
  • Can you give a small example of data that will reproduce this error? - MaxU
  • I understand he does not like the type of data columns sex and race yadi.sk/i/T5m20vOm5Lkh1w . It is necessary to convert them into strings judging by the error. Doing so nothing helps yadi.sk/i/Rz4JQ7hUPmzX0Q - IT-KOT
  • one
    I apologize for the false alarm. Here is your code in my editor: print(df.query("race=='Amer-Indian-Eskimo' and sex=='Male'")['age'].max()) but this is how I originally wrote it host print(df.query('race' == 'Amer-Indian-Eskimo' and 'sex' == 'Male')['age'].max()) . Now everything works. In general, I made a mistake syntakis - IT-KOT

So I sort of figured it out myself.

 print(df[(df['race'] == 'Amer-Indian-Eskimo') & (df['sex'] == 'Male')]['age'].max()) 

Correct if I'm wrong.

  • Yes that's right. Understood) - IT-KOT