微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

删除包含特定值的行之后的pandas DataFrame行

如何解决删除包含特定值的行之后的pandas DataFrame行

我正在尝试删除yes列中有'Ammend'的行之后的所有行

df:

  Ammend
 0  no
 1  yes
 2  no
 3  no
 4  yes
 5  no

必需的输出df:

  Ammend
 0  no
 1  yes
 3  no
 4  yes

看下面的代码

df = df.drop(df[df['Amended' == 'yes']],inplace=True)

返回一条KeyError: False错误消息

我尝试使用.index.tolist().loc之类的不同方法对此进行了许多不同的变化 但我似乎还是无法弄清楚。

我也尝试过截断:

filings_df.truncate(after=filings_df.loc[filings_df['Filings'] == '10-K/A'].index[0],before = filings_df.loc[filings_df['Filings'] == '10-K/A'].index[1])

这将返回:

IndexError:索引1超出了大小为1的轴0的边界

解决方法

尝试一下

import pandas as pd
import numpy as np

np.random.seed(525)
df = pd.DataFrame({'Other': np.random.rand(10),'Ammend': np.random.choice(['yes','no'],10)})
df
      Other Ammend
0  0.750282     no
1  0.379455     no
2  0.766467    yes
3  0.351025     no
4  0.965993     no
5  0.709159     no
6  0.838831    yes
7  0.218321     no
8  0.573360    yes
9  0.738974     no

输出:

df.drop(index=df[df['Ammend'].shift() == 'yes'].index)

      Other Ammend
0  0.750282     no
1  0.379455     no
2  0.766467    yes
4  0.965993     no
5  0.709159     no
6  0.838831    yes
8  0.573360    yes
,

结合使用pandas.Series.neshift技巧的一种方法:

s = df["Ammend"]
new_df = df[~s.ne(s.shift()).cumsum().duplicated(keep="first")]
print(new_df)

输出:

  Ammend
0     no
1    yes
2     no
4    yes
5     no

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。