python - pandas -- 删除包含 nans 的行 -- 忽略列

标签 python pandas

我希望能够从数据帧 ( orig ) 中删除与包含 filtered 的派生数据帧 ( NaN ) 中的行相对应的行。他们身上的值(value)观。问题在于派生数据帧有一个已删除的列,导致每一行都被删除。要修改此问题,我必须重新插入已删除的列。有没有比重新插入 filtered 更优雅的方法来实现所需的结果?从中删除的列?

>>> orig = pd.DataFrame([
                         [1, 1.0, 'one'], 
                         [2, 2.0, 'two'],
                         [100, 100.0, 'one-hundred']
                        ], columns=['Integers', 'Floats', 'Strings'])
>>> numeric = orig.select_dtypes(include=['int', 'float'])
>>> numeric
   Integers  Floats
0         1     1.0
1         2     2.0
2       100     100.0
>>> filtered = numeric[np.abs(numeric - numeric.mean())<=(numeric.std())].dropna()
>>> filtered
   Integers  Floats
0       1.0     1.0
1       2.0     2.0

下一行将返回一个空数据框,因为 filtered没有列 Strings其中,因此排除 orig 中的每一行.

>>> removed_rows = orig[orig.isin(filtered)].dropna()

在运行上面的代码行之前,我必须重新插入第二行中删除的非数字列:

>>> filtered['Strings'] = orig['Strings']

最终得到想要的结果:

>>> removed_rows
   Integers  Floats Strings
0       1.0     1.0     one
1       2.0     2.0     two

如果这是执行此操作的唯一方法,那么那很好 - 但我希望有一种更优雅的方法来执行此操作。有吗?

最佳答案

使用DataFrame.all检查每行的所有 True:

orig[(np.abs(numeric - numeric.mean()) <= (numeric.std())).all(axis=1)] 

在 pandas 0.23.0 中,由于某种原因 numeric 仅返回列 float

print (orig.dtypes)
Integers      int64
Floats      float64
Strings      object
dtype: object

print (orig.select_dtypes(include=['int', 'float']))
   Floats
0     1.0
1     2.0
2   100.0

所以更好的是使用np.number:

print (orig.select_dtypes(include=np.number))
   Integers  Floats
0         1     1.0
1         2     2.0
2       100   100.0

关于python - pandas -- 删除包含 nans 的行 -- 忽略列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50786949/

相关文章:

python - 数据框的填充列

Python - Pandas 描述抛出错误 : unhashable type 'dict'

python - google-cloud 使用 python api 获取实例 ID 和区域

python - 删除多索引级别但保留列名 - pandas

python - matplotlib 和子图属性

python - 根据单列删除 CSV 文件的重复行

python - 如何创建唯一值计数的汇总表?

python - 根据列表中的值向 DataFrame 添加新列

Python PIL 难以处理未压缩的 16 位 TIFF 图像

python - 如何在 pyspark 中创建具有随机值的新列?