python-3.x - 如何在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 行。
解决方案
基于您的示例数据框的几个假设:
- 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
希望对您有所帮助,您可以根据需要修改功能。
推荐阅读
- python - Visual Studio 代码 - 执行代码失败:错误:调试单元需要 Pip 模块 ptvsd。您需要安装它来调试单元
- javascript - 如何设置构造函数的原型?
- c++ - 为什么这段代码不利于计算功率(效率较低)?
- python - 如何解决使用 changeTarget 命令时的路由替换错误?
- c - 网络编程,从客户端发送文件到服务器
- apache-flink - 为什么 Flink 不重试算子失败?
- java - 仅在具有 Windows 身份验证的两种情况之一中失败时如何解决“登录失败”错误(JDBC Java)
- python - 如何从羽毛字节对象读入数据帧
- sql - 需要帮助来理解下面的 oracle 代码
- python - Scipy 正弦拟合有错误的偏移量