计算数字列 Pandas 中的字符串值

Dav*_*321 4 python-3.x pandas data-cleaning

我有一个数据框:

    Name    Hours_Worked
1   James   3
2   Sam     2.5
3   Billy   T
4   Sarah   A
5   Felix   5
Run Code Online (Sandbox Code Playgroud)

第一,如何计算具有非数字值的行数?

第二,如何过滤以识别包含非数字值的行?

jez*_*ael 6

使用to_numericerrors='coerce'用于将非数字以NaNs,不创建规则isna

mask = pd.to_numeric(df['Hours_Worked'], errors='coerce').isna()
#oldier pandas versions
#mask = pd.to_numeric(df['Hours_Worked'], errors='coerce').isnull()    
Run Code Online (Sandbox Code Playgroud)

然后True通过sum以下方式计算s 值:

a = mask.sum()
print (a)
2
Run Code Online (Sandbox Code Playgroud)

并过滤boolean indexing

df1 = df[mask]
print (df1)
    Name Hours_Worked
3  Billy            T
4  Sarah            A
Run Code Online (Sandbox Code Playgroud)

详情

print (mask)
1    False
2    False
3     True
4     True
5    False
Name: Hours_Worked, dtype: bool
Run Code Online (Sandbox Code Playgroud)

检查数字的另一种方法:

def check_num(x):
    try:
        float(x)
        return False        
    except ValueError:
        return True

mask = df['Hours_Worked'].apply(check_num)
Run Code Online (Sandbox Code Playgroud)

  • @RafaelC - 因为浮点数,它只适用于整数。 (2认同)