首页 > 解决方案 > 如何在python中删除数据框中的初始行

问题描述

我有 4 个数据框,其中包含 4 种产品一年的每周销售价值。一些初始行是 0,因为没有销售。在几周之间还有一些其他的 0 值。我想删除那些初始的 0 值,保持在 0 之间。

例如

Week Sales(prod 1)           
1       0
2       0
3       100
4       120
5       55
6       0
7       60.

Week Sales(prod 2)           
1       0
2       0
3       0
4       120
5       0
6       30
7       60.

我想从第一个表中删除第 1,2 行和第 2 个表中的第 1,2,3 行。

标签: python-3.x

解决方案


基于您的示例数据框的几个假设:

  • DataFrame 是使用 pandas 创建的
  • 周总是从 1 开始
  • 将仅删除所有销售量为 0 的起始周

解决方案:

需要 Python 库 - pandas、more_itertools

示例数据框(df):

Week Sales         
1       0
2       0
3       0
4       120
5       0
6       30
7       60

蟒蛇代码:

import pandas as pd
import more_itertools as mit

filter_col = 'Sales'
filter_val = 0

##function which returns the index to be removed
def return_initial_week_index_with_zero_sales(df,filter_col,filter_val):
    index_wzs = [False]
    if df[filter_col].iloc[1]==filter_val:
        index_list = df[df[filter_col]==filter_val].index.tolist()
        index_wzs = [list(group) for group in mit.consecutive_groups(index_list)]
    else:
        pass
    return index_wzs[0]

##calling above function and removing index from the dataframe
df = df.set_index('Week')
weeks_to_be_removed = return_initial_week_index_with_zero_sales(df,filter_col,filter_val)
if weeks_to_be_removed:
    print('Initial weeks with 0 sales are {}'.format(weeks_to_be_removed))
    df = df.drop(index=weeks_to_be_removed)
else:
    print('No initial week has 0 sales')

df.reset_index(inplace=True)
Result:df
Week Sales
4    120
5    55
6    0
7    60

希望对您有所帮助,您可以根据需要修改功能。


推荐阅读