bil*_*ard 4 python string int numpy pandas
我有一个如下所示的数据框
a b
0 1 26190
1 5 python
2 5 580
Run Code Online (Sandbox Code Playgroud)
我想让列b
只承载整数,但正如你所看到的,python
它不是 int 可转换的,所以我想删除 index 处的行1
。我的预期输出必须像
a b
0 1 26190
1 5 580
Run Code Online (Sandbox Code Playgroud)
如何在python中使用pandas过滤和删除?
您可以使用to_numeric
withnotnull
和过滤器boolean indexing
:
print (pd.to_numeric(df.b, errors='coerce'))
0 26190.0
1 NaN
2 580.0
Name: b, dtype: float64
print (pd.to_numeric(df.b, errors='coerce').notnull())
0 True
1 False
2 True
Name: b, dtype: bool
df = df[pd.to_numeric(df.b, errors='coerce').notnull()]
print (df)
a b
0 1 26190
2 5 580
Run Code Online (Sandbox Code Playgroud)
Boud评论的另一个解决方案- 使用to_numeric
withdropna
并最后转换为int
by astype
:
df.b = pd.to_numeric(df.b, errors='coerce')
df = df.dropna(subset=['b'])
df.b = df.b.astype(int)
print (df)
a b
0 1 26190
2 5 580
Run Code Online (Sandbox Code Playgroud)
如果需要检查所有具有错误数据的行,请使用isnull
- 在应用函数to_numeric
get后过滤所有数据NaN
:
print (pd.to_numeric(df.b, errors='coerce').isnull())
0 False
1 True
2 False
Name: b, dtype: bool
print (df[pd.to_numeric(df.b, errors='coerce').isnull()])
a b
1 5 python
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
22949 次 |
最近记录: |