python – Groupby比Pandas更慢

我将下表作为熊猫数据帧.我需要计算所有零件编号,其中净销售额大于给定零件的推荐价格.

输入:above_master

  Short Number  Net Sales    Part Number   Recommended Price
0       MU2146     413.25      MU2146      385.949155
1       MU2146     433.12      MU2146      385.949155
2       MU2146     498.12      MU2146      385.949155
3       MU1609     146.07      MU1609      149.138978
4       MU1609     246.17      MU1609      149.138978

要求的输出

Part Number count
MU2146       3 
MU1609       1

使用的代码

for number in range(len(above_master.index)):
    cal_s1 = above_master[above_master['Net Sales'] > above_master.iloc[number]['Recommended Price'] ].groupby('Part Number')['Recommended Price'].count()
    cal_s2 = cal_s1.to_frame().reset_index()
    cal_s3 = cal_s2.loc[cal_s2['Part Number'] == above_master.iloc[number]['Part Number']]
    cal_s4 = cal_s4.append(cal_s3, ignore_index=True)

这很好,但需要很长时间.

最佳答案 使用大小的loc:

df.loc[df['Recommended Price'].lt(df['Net Sales'])].groupby('Part Number').size()
Part Number
MU1609    1
MU2146    3
dtype: int64
点赞