如何用python计算上个月的最高总销售额

2024-04-19 18:42:47 发布

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

我有一个数据帧名为store_数据.csv在数据帧中有数千个数据。样本数据如下-

Date       Store1   Store2   Store3   Store4
2018-06-01 2643     1642     2678     3050
2018-07-16 6442     5413     5784     7684
2018-07-24 4587     5743     3948     6124
2018-08-12 3547     8743     7462     8315

如何计算python中最后一个月数据的最高总销售额?在


Tags: csv数据storedate样本销售额store1store2
2条回答

首先创建DatetimeIndex

#if necessary
#df = df.set_index('Date')
#df['Date'] = pd.to_datetime(df['Date'])

print (df)
            Store1  Store2  Store3  Store4
Date                                      
2018-06-01    2643    1642    2678    3050
2018-07-16    6442    5413    5784    7684
2018-08-10    4587    5743    3948    6124 <-change date for better sample
2018-08-12    3547    8743    7462    8315

print (df.index)
DatetimeIndex(['2018-06-01', '2018-07-16', '2018-08-10', '2018-08-12'], 
              dtype='datetime64[ns]', name='Date', freq=None)

然后按^{}转换为月份:

^{pr2}$

按最后一个值筛选,sum和最后一个按最大值^{}获取列名:

print (df1.loc[df1.index[-1]].sum())
Store1     8134
Store2    14486
Store3    11410
Store4    14439
dtype: int64

out = df1.loc[df1.index[-1]].sum().idxmax()
print (out)
Store2

谢谢你,@Jon Clements提供了另一个解决方案:

out = df.last('M').resample('M').sum().T.idxmax()
#if need scalar output
out = df.last('M').resample('M').sum().iloc[0].idxmax()

这个解决方案是针对你的问题的,有点老套,但我已经测试过了,似乎对我有用。在

这个程序将找到上个月销售额最高的商店。这个程序假设月份是按顺序排列的(数据不是混合的)。如果这是个问题,请把问题修改得更具体一点,我看看我能做些什么。一种可能的实现方法是使用dictionary跟踪每个月,然后访问上一个月的数据以找到最大值

import re

def get_highest_sales(filename):
    sales_during_month = [0, 0, 0, 0]
    with open(filename) as f:
        f.readline() # Skip first line
        prev_month = ""
        for line in f:
            cleaned = re.sub(" +", ' ', line)
            values = cleaned.split(' ')
            month  = values[0].split('-')[1]
            if not month == prev_month:
                prev_month = month
                sales_during_month = [0, 0, 0, 0]
            sales = [float(sale) for sale in values[1:]]
            for store,sale in enumerate(sales):
                sales_during_month[store] += sale

    return "Store: " + str(sales_during_month.index(max(sales_during_month)) + 1)

相关问题 更多 >