第一列是产品名称,第二列是星期数,后面是每周的数据。

现在需要保留每个产品相对应的星期数的数据,后面的就删除。比如:productA保留3周的数据,productB保留7周的数据。
第一步:导入库并读入数据:

第二步:建立迭代遍历每行,并将每行的Number_of_week读取出来。

第三步:再建立迭代遍历每行不需要的数据,并将不需要的数据删除。

为什么要有(j+1,10,1)呢?
j是从数据里读出的要保留的星期数,j+1就是要从第一个不要的数据开始迭代,直到第9周,所以中间的数据是10(np.arange生成的序列不包含最后一个数字),步长是1。
df.loc[k]是一行数据,提取处理就是Series数据类型,要删除里面的数据需要用到.drop(index)。这里的索引是week加数字,数字用%d代替,后面再用%i指明具体是哪个数字。
如果列名不规则,请在第一步提取数据的时候重新设定列名,用0,1,2,3,......这样就方便处理了。


这个问题很简单,解决的代码也没超过10行,但是却解决了大问题,比较在实际使用的过程中的表格可能是有好几十列的上百行的,手动删除会很麻烦,而且容易出错。

为了重复利用,也可以改写成自定义函数:

网友评论