如何将无效的数据类型输入替换为熊猫数据框中的“无”

时间:2019-04-18 06:49:05

标签: python python-3.x

要替换“数字”和“日期”列中的所有无效数据类型。初始表是这样的:

name    number      date
a       1.2         123.2
b       123.2       3/13/2019
c       2.3         3/14/2019
d       569         3/15/2019
e       abc         3/15/2019
f       30          abc 
g       39.8        -3
h       3/21/2019   3/19/2019
i       -395        3/20/2019
j       4           3/21/2019

清理后,该表应如下所示:所有无效的数据类型输入已被替换为无:

name    number      date
a       1.2         
b       123.2       3/13/2019
c       2.3         3/14/2019
d       569         3/15/2019
e                   3/15/2019
f       30           
g       39.8        
h                   3/19/2019
i       -395        3/20/2019
j       4           3/21/2019

我只能将字符串输入替换为None,我不知道如何在“日期”列中将数字输入替换为“无”,也不知道如何将日期时间输入替换为“无”  在“数字”列中。如果datetime列中有数字输入或number列中有日期时间输入,我的代码将显示错误:

“浮动”对象没有属性“ strftime”

从datetime2数据类型到datetime数据类型的转换导致值超出范围。

df['date']=df['date'].apply(lambda x: None if str(type(x))=="<class 'str'>" else x)

df['date']=df['date'].apply(lambda x: x.strftime('%m/%d/%Y')if not pd.isnull(x) else '')

df['date'] = pd.to_datetime(df['date'], errors='coerce')

df['number'] = df['number'].apply(lambda x: None if str(type(x))=="<class 'str'>" else x)

1 个答案:

答案 0 :(得分:0)

可能有更好的方法,但是我想到的方法是使用正则表达式。这是解决方案。

$(document.body).on('focus', '.currsearch', function(){
    $(this).autocomplete({
         source : function(request, response){
                var filteredArray = $.map(allCurrency, function(item) {
                  if(item.indexOf(request.term.toUpperCase()) == 0){
                        return item;
                      }
                  else{
                          return null;
                      }
              });                           
                response(filteredArray);
            },
            open : function(event, ui)
            {
                $(".ui-autocomplete").css("z-index", 9999);
            },
            change : function(event, ui)
            {
                formChangeFlag = true;
                if (!ui.item && $(this).val() != "")
                {
                    alert("Please input valid currency.");
                    $(this).val("");
                    $(this).focus();
                }
            }
    });     
    $(this).autocomplete("search", $(this).val());      
});