Abdulaziz G
Abdulaziz G

Reputation: 13

Trying to to print only even values of a column Dataframe in pandas

This is the dataframe:

exam_data  = {'name': ['Anastasia', 'Dima', 'Katherine', 'James', 'Emily', 'Michael', 'Matthew', 'Laura', 'Kevin', 'Jonas'],
        'score': [12.5, 9, 16.5, np.nan, 9, 20, 14.5, np.nan, 8, 19],
        'attempts': [1, 3, 2, 3, 2, 3, 1, 1, 2, 1],
        'qualify': ['yes', 'no', 'yes', 'no', 'no', 'yes', 'yes', 'no', 'no', 'yes']}
labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j']

I'm trying to print only even values of a column named "attempts"
is there a function I can use? such as:

df["attempts"].even()

Upvotes: 1

Views: 825

Answers (3)

GabrielP
GabrielP

Reputation: 782

You can try with the following:

print(df[df['attempts']%2==0]['attempts'].values)

Upvotes: 0

jezrael
jezrael

Reputation: 863156

Use DataFrame.loc for filter by mask - compare modulo 2 with 0 and column name:

df = pd.DataFrame(exam_data)

print (df.loc[df.attempts % 2 == 0, 'attempts'])
2    2
4    2
8    2
Name: attempts, dtype: int64

For odd values compare by 1:

print (df.loc[df.attempts % 2 == 1, 'attempts'])
0    1
1    3
3    3
5    3
6    1
7    1
9    1
Name: attempts, dtype: int64

Upvotes: 2

Mustafa Aydın
Mustafa Aydın

Reputation: 18316

You can use

df.attempts[df.attempts % 2 == 0]

If you look at df.attempts % 2 == 0, you'll see it is a series of Trues and Falses. Then we use it as a boolean mask to select desired entries which give "0 as remainder when divided by 2" i.e., even ones.

Upvotes: 2

Related Questions