pandas 如何根据 dtype 删除 DataFrame 列

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48817592/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:11:34  来源:igfitidea点击:

How to drop DataFrame columns based on dtype

pythonpandas

提问by Nick Duddy

I've got a pandas dataframe and I'm trying to drop all the object fields from so that I'm left with only numeric.

我有一个 Pandas 数据框,我试图从中删除所有对象字段,这样我就只剩下数字了。

I've been trying to write a for loop to do this task, as I'm likely going to need to do it over and over again with different data.

我一直在尝试编写一个 for 循环来完成此任务,因为我可能需要使用不同的数据一遍又一遍地执行此操作。

For some reason I can't get it working. Below is what I've did so far

出于某种原因,我无法让它工作。以下是我到目前为止所做的

for cols in data:
    if data.values.type == object:
        numdata = data.drop(axis=1, inplace=True)

The error I get is:

我得到的错误是:

AttributeError Traceback (most recent call last) in () 1 for cols in data: ----> 2 if data.values.type == object: 3 numdata = data.drop(axis=1, inplace=True)

AttributeError: 'numpy.ndarray' object has no attribute 'type'

AttributeError Traceback(最近一次调用最后一次) in () 1 for cols in data: ----> 2 if data.values.type == object: 3 numdata = data.drop(axis=1, inplace=True)

AttributeError: 'numpy.ndarray' 对象没有属性 'type'

I am a newb and for some reason I can't get the for loop and if statement logic to stick in my head.

我是一个新手,出于某种原因,我无法将 for 循环和 if 语句逻辑留在我的脑海中。

回答by roganjosh

You can use select_dtypesto exclude columns of a particular type.

您可以使用select_dtypes排除特定类型的列。

import pandas as pd

df = pd.DataFrame({'x': ['a', 'b', 'c'], 'y': [1, 2, 3], 'z': ['d', 'e', 'f']})

df = df.select_dtypes(exclude=['object'])
print(df)