如何执行多个数学运算来派生新列?

我有一个 df 看起来像这样:


consumer_id      order_total

1                    5

2                    6

3                    7

1                    5

对于每一个消费者consumer_id我想取平均值所有的order_total每consumer_id创造一个新的列SID基于以下规则:


if new `order_total` >= 7:

      SID = 3

elif new `order_total` >= 6 OR <7:

      SID = 2

else:

      SID = 1

新 df 应如下所示(consumer_id1,平均值为 5):


consumer_id      order_total   SID

1                    5          1

2                    6          2

3                    7          3

1                    5          1

这是我在没有平均 per 的情况下尝试的 if 语句consumer_id:


if df.order_total >= 150:

    df['SID'] = 3

elif [df.order >= 50] & [df.order< 100]:

    df['SID'] = 2

else:

    df['SID'] = 1

我得到错误:


ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().


梵蒂冈之花
浏览 181回答 3
3回答

MYYA

尝试apply:def f(x):&nbsp; &nbsp; if x >= 7:&nbsp; &nbsp; &nbsp; &nbsp; SID = 3&nbsp; &nbsp; elif x >= 6 and x<7:&nbsp; &nbsp; &nbsp; &nbsp; SID = 2&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; SID = 1&nbsp; &nbsp; return SIDdf['SID']=df['order_total'].apply(f)

忽然笑

使用 groupby 和 transform 来获取包含每个 consumer_id 的平均订单总数的系列,然后将函数应用于该系列以创建结果系列。def sid_assign(x):&nbsp; &nbsp; if x >= 7:&nbsp; &nbsp; &nbsp; &nbsp; return 3&nbsp; &nbsp; if x >= 6 | x < 7:&nbsp; &nbsp; &nbsp; &nbsp; return 2&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; return 1id_sums = df.groupby('consumer_id').order_total.transform('mean')df['SID'] = id_sums.apply(sid_assign)print(df)&nbsp; &nbsp;consumer_id&nbsp; order_total&nbsp; SID0&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 5&nbsp; &nbsp; 11&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 2&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 6&nbsp; &nbsp; 22&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 3&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 7&nbsp; &nbsp; 33&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 1&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; 5&nbsp; &nbsp; 1
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python