python - 如何在 Pandas 数据框中获取数字列名

标签 python pandas

我有 pandas 数据框,它有 object,int64,float64 数据类型。我想获取 int64 和 float64 列的列名。我在 Pandas 中使用以下命令,但它似乎不起作用

cat_num_prv_app = [num for num in list(df.columns) if isinstance(num, (np.int64,np.float64))]

以下是我的数据类型

 df.info()
 <class 'pandas.core.frame.DataFrame'>
 RangeIndex: 1670214 entries, 0 to 1670213
 Data columns (total 37 columns):
 ID               1670214 non-null int64
 NAME             1670214 non-null object
 ANNUITY          1297979 non-null float64
 AMOUNT           1670214 non-null float64
 CREDIT           1670213 non-null float64

我想将列名 ID、ANNUITY、AMOUNT 和 CREDIT 存储在一个变量中,稍后我可以使用它来对数据框进行子集化。

最佳答案

使用select_dtypes使用 np.number 选择所有数字列:

df = pd.DataFrame({'A':list('abcdef'),
                   'B':[4.5,5,4,5,5,4],
                   'C':[7.4,8,9,4,2,3],
                   'D':[1,3,5,7,1,0],
                   'E':list('aaabbb')})

print (df)
   A    B    C  D  E
0  a  4.5  7.4  1  a
1  b  5.0  8.0  3  a
2  c  4.0  9.0  5  a
3  d  5.0  4.0  7  b
4  e  5.0  2.0  1  b
5  f  4.0  3.0  0  b

print (df.dtypes)
A     object
B    float64
C    float64
D      int64
E     object
dtype: object

cols = df.select_dtypes([np.number]).columns
print (cols)
Index(['B', 'C', 'D'], dtype='object')

这里可以指定float64int64:

df = pd.DataFrame({'A':list('abcdef'),
                   'B':[4.5,5,4,5,5,4],
                   'C':[7,8,9,4,2,3],
                   'D':[1,3,5,7,1,0],
                   'E':list('aaabbb')})

df['D'] = df['D'].astype(np.int32)
print (df.dtypes)
A     object
B    float64
C      int64
D      int32
E     object
dtype: object

cols = df.select_dtypes([np.int64,np.float64]).columns
print (cols)
Index(['B', 'C'], dtype='object')

关于python - 如何在 Pandas 数据框中获取数字列名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51684585/

相关文章:

Python:为 csv.DictWriter 设置引号?

python - 如何使用另一列列表中的特定元素填充数据框中的空列?

python - 仅选择在特定时间发生的行

python - IndexError : list index out of range when in python, 即使范围存在

python - 只读 python 属性?无法打印对象

python - 如何使用 Python 发送电子邮件?

python - 在 Python 数据框中按年度填补空白的最佳方法

python - 多索引数据框中列之间的数学运算

python - Arduino 从不断更新的文件中读取

python - 如何使用 Python 绘制能量排名图?