Skip to main content
 首页 » 编程设计

python之根据名称删除数据框行

2024年10月24日11itcoder

我有以下数据框 df,我试图将所有具有 curv_typ 的行删除为 PYC_RT 或 YCIF_RT。

    curv_typ   maturity    bonds  2015M06D19   2015M06D18   2015M06D17   \ 
0     PYC_RT       Y1    GBAAA        -0.24        -0.25        -0.23    
1     PYC_RT       Y1  GBA_AAA        -0.05        -0.05        -0.05    
2     PYC_RT      Y10    GBAAA         0.89         0.92         0.94 

我的代码如下。但是,由于某些原因,df 在运行以下代码后结果与上面完全相同:

df = pd.DataFrame.from_csv("ECB.tsv", sep="\t", index_col=False) 
df[df["curv_typ"] != "PYC_RT"] 
df[df["curv_typ"] != "YCIF_RT"] 

请您参考如下方法:

使用isin并否定 ~ 掩码的 bool 条件:

In [76]: 
df[~df['curv_typ'].isin(['PYC_RT', 'YCIF_RT'])] 
 
Out[76]: 
Empty DataFrame 
Columns: [curv_typ, maturity, bonds, 2015M06D19, 2015M06D18, 2015M06D17] 
Index: [] 

请注意,这不会在您的示例数据集上返回任何内容