尝试仅打印数据框中列的偶数值

2024-09-27 20:19:11 发布

您现在位置:Python中文网/ 问答频道 /正文

这是数据帧:

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']

我试图只打印名为“尝试”的列的偶数值
有我可以使用的功能吗? 例如:

df["attempts"].even()

Tags: 数据nonamedatanpnanyesexam
3条回答

^{}用于按掩码筛选-将模2与0和列名进行比较:

df = pd.DataFrame(exam_data)

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

对于奇数值,通过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

你可以用

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

如果你看一下df.attempts % 2 == 0,你会看到它是一系列的TrueFalse。然后,我们使用它作为布尔掩码来选择所需的条目,这些条目给出“0除以2时的余数”,即偶数

您可以尝试以下方法:

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

相关问题 更多 >

    热门问题