df.drop 如果存在 [英] df.drop if it exists

查看:66
本文介绍了df.drop 如果存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面是一个函数,它接受一个文件并删除列名row_num"、start_date"、end_date".

Below is a function that takes a file and drops column names 'row_num", 'start_date', 'end_date.'

问题是不是每个文件都有这些列名,所以函数返回一个错误.

The problem is not every file has each of these column names, so the function returns an error.

我的目标是修改代码,以便在这些列存在时删除这些列,但在该列不存在时不返回错误.

My goal is to alter code so that it removes these columns if it exists but does not return an error if the column does not exist.

def read_df(file):
    df = pd.read_csv(file, na_values=['', ' '])
    # Drop useless junk and fill empty values with zero 
    df = df.drop(['row_num','start_date','end_date','symbol'], axis=1).fillna(0)
    df=df[df!=0][:-1].dropna().append(df.iloc[-1])
    return df

推荐答案

将参数 errors 添加到 DataFrame.drop:

Add parameter errors to DataFrame.drop:

错误:{'ignore', 'raise'},默认为'raise'

errors : {'ignore', 'raise'}, default 'raise'

如果为忽略",则抑制错误并仅删除现有标签.

If 'ignore', suppress error and only existing labels are dropped.

df = df.drop(['row_num','start_date','end_date','symbol'], axis=1, errors='ignore')

示例:

df = pd.DataFrame({'row_num':[1,2], 'w':[3,4]})
df = df.drop(['row_num','start_date','end_date','symbol'], axis=1, errors='ignore')
print (df)
   w
0  3
1  4

这篇关于df.drop 如果存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆