sto*_*eld 5 python data-quality pandas
我正在使用 pandas 编写一个数据质量脚本,该脚本将检查每列的某些条件
目前我需要找出特定列中没有小数或实际数字的行。如果数字是整数,我可以找到它,但是到目前为止我所看到的方法(ieisdigit() , isnumeric(), isdecimal()等)无法正确识别该数字何时是十进制数。例如:2.5、0.1245 等。
以下是一些示例代码和数据:
>>> df = pd.DataFrame([
[np.nan, 'foo', 0],
[1, '', 1],
[-1.387326, np.nan, 2],
[0.814772, ' baz', ' '],
["a", ' ', 4],
[" ", 'foo qux ', ' '],
], columns='A B C'.split(),dtype=str)
>>> df
A B C
0 NaN foo 0
1 1 1
2 -1.387326 NaN 2
3 0.814772 baz
4 a 4
5 foo qux
>>> df['A']
0 NaN
1 1
2 -1.387326
3 0.814772
4 a
5
Name: A, dtype: object
Run Code Online (Sandbox Code Playgroud)
以下方法均无法识别小数
df['A'].fillna('').str.isdigit()
df['A'].fillna('').str.isnumeric()
df['A'].fillna('').str.isdecimal()
0 False
1 True
2 False
3 False
4 False
5 False
Name: A, dtype: bool
Run Code Online (Sandbox Code Playgroud)
所以当我尝试以下操作时我只得到 1 行
>>> df[df['A'].fillna('').str.isdecimal()]
A B C
1 1 1
Run Code Online (Sandbox Code Playgroud)
注意:我正在使用dtype=strpandas 来获取数据而不解释/更改 dtypes 的值。实际数据在 A 列中可能有空格,我将使用 Replace() 删除它,我在这里保持代码简单以免混淆。
使用to_numericwitherrors='coerce'将非数字转为NaNs,然后通过 进行测试Series.notna:
print (pd.to_numeric(df['A'], errors='coerce').notna())
0 False
1 True
2 True
3 True
4 False
5 False
Name: A, dtype: bool
Run Code Online (Sandbox Code Playgroud)
如果需要返回True缺失值:
print (pd.to_numeric(df['A'], errors='coerce').notna() | df['A'].isna())
0 True
1 True
2 True
3 True
4 False
5 False
Name: A, dtype: bool
Run Code Online (Sandbox Code Playgroud)
另一种具有自定义功能的解决方案:
def test_numeric(x):
try:
float(x)
return True
except Exception:
return False
print (df['A'].apply(test_numeric))
0 True
1 True
2 True
3 True
4 False
5 False
Name: A, dtype: bool
print (df['A'].fillna('').apply(test_numeric))
0 False
1 True
2 True
3 True
4 False
5 False
Name: A, dtype: bool
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4266 次 |
| 最近记录: |