python - 如何从 Python 中的数据框中排除非数字整数

标签 python numpy scipy ipython

我有一个数据框,它包含整数、字符串、数字等数据类型。 像下面这样的东西。我想排除所有非数字变量。 Python 有什么自动化的方法吗?

'data.frame':   891 obs. of  12 variables:
 $ PassengerId: int  1 2 3 4 5 6 7 8 9 10 ...
 $ Survived   : int  0 1 1 1 0 0 0 0 1 1 ...
 $ Pclass     : int  3 1 3 1 3 3 1 3 3 2 ...
 $ Name       : Factor w/ 891 levels "Abbing, Mr. Anthony",..: 109 191 358 277 16 559 520 629 417 581 ...
 $ Sex        : Factor w/ 2 levels "female","male": 2 1 1 1 2 2 2 2 1 1 ...
 $ Age        : num  22 38 26 35 35 NA 54 2 27 14 ...
 $ SibSp      : int  1 1 0 1 0 0 0 3 0 1 ...
 $ Parch      : int  0 0 0 0 0 0 0 1 2 0 ...
 $ Ticket     : Factor w/ 681 levels "110152","110413",..: 524 597 670 50 473 276 86 396 345 133 ...
 $ Fare       : num  7.25 71.28 7.92 53.1 8.05 ...
 $ Cabin      : Factor w/ 148 levels "","A10","A14",..: 1 83 1 57 1 1 131 1 1 1 ...
 $ Embarked   : Factor w/ 4 levels "","C","Q","S": 4 2 4 4 4 3 4 4 4 2 ...

排除数字变量后,我的数据框应如下所示:

'data.frame':   891 obs. of  12 variables:
 $ PassengerId: int  1 2 3 4 5 6 7 8 9 10 ...
 $ Survived   : int  0 1 1 1 0 0 0 0 1 1 ...
 $ Pclass     : int  3 1 3 1 3 3 1 3 3 2 ...
 $ Age        : num  22 38 26 35 35 NA 54 2 27 14 ...
 $ SibSp      : int  1 1 0 1 0 0 0 3 0 1 ...
 $ Parch      : int  0 0 0 0 0 0 0 1 2 0 ...
 $ Fare       : num  7.25 71.28 7.92 53.1 8.05 ...

最佳答案

我们可以使用._get_numeric_data()

import pandas as pd #import the pandas library
#creating a small dataset for testing
df1 = pd.DataFrame({'PassengerId' :  [1, 2, 3], 
        'Name' : ['Abbing, Mr. Anthony', 'Ann, C', 'John, H'], 
        'Fare' : [7.25, 71.28, 7.92]})
#extract only the numeric column types
df2 = df1._get_numeric_data()
print(df2)

或者另一种选择是 select_dtypes()

df3 = df1.select_dtypes(include = ['int64', 'float64'])
print(df3)

关于python - 如何从 Python 中的数据框中排除非数字整数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33705180/

相关文章:

python - Pandas 将具有不同参数值的函数应用于不同的列

python - 如何将 numpy 数组发送到 Armadillo (C++) 并从 Armadillo 返回一个 numpy 数组

python - Python 中带边界的向量化随机游走

python - 在 Python 中使用兰伯特函数时的 NaN 值 - 在 Enthought Canopy 中

python - pip 如何在 windows 7 x64 python 2.7 上安装 pylzma

python - 有没有比循环 numpy 数组更快的方法?

python - 数组的最内部维度

python - 在python中将日期截断为上周一或一周中的任何一天

python - scipy.optimize.leastsq 返回最佳猜测参数而不是新的最适合

python - 如何在不使用循环的情况下反转 Python 中列表的顺序?