如何使用 lambda 函数逐行计算值?

时间:2021-06-22 21:17:16

标签: python pandas lambda

所以我有一个数据框,我想在其中计算学生在场的所有天数。数据帧标题是一个月中的几天,我想计算字符 'P' 行在所有列上的频率,并将它们存储在一个新列中。我现在所做的是定义一个函数,它应该接受每一行并计算 P 的频率 -

def count_P(list):
    frequency = 0
    for item in list:
        if item == 'P':
            frequency += 1
    return frequency  

然后我试图应用这个功能,这让我感到困惑:

df['Attendance'] = df.apply(lambda x: count_P(x) for x in , axis = 1)

在上面的行中,我每次都需要将 x 作为数据帧的一行传递,所以我要写
for x in range(df.iloc[0],df.iloc[df.shape[0]])?但这给了我SyntaxError。我这里需要轴吗?还是需要通过其他方式来完成?

编辑: 我收到的错误消息-

df['Attendance'] = df.apply(lambda x: count_P(x) for x in range(df.iloc[0],df.iloc[df.shape[0]]),axis=1)
                                ^
SyntaxError: Generator expression must be parenthesized

1 个答案:

答案 0 :(得分:4)

假设您的数据框如下所示:

df = pd.DataFrame({'2021-03-01': ['P','P'], '2021-03-02': ['P','X']})

你可以这样做:

df["p_count"] = (df == 'P').sum(axis=1)

产量:

    2021-03-01  2021-03-02  p_count
0   P           P           2
1   P           X           1
相关问题