如何基于dtype删除DataFrame列 [英] How to drop DataFrame columns based on dtype
问题描述
我有一个pandas数据框,我试图从中删除所有对象字段,以便只剩下数字.
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.
我一直在尝试编写一个for循环来完成此任务,因为我可能需要一遍又一遍地对不同的数据进行处理.
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 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)
我得到的错误是:
AttributeError跟踪(最近的调用) 最后)在() 数据中的cols为1: ----> 2如果data.values.type == object: 3 numdata = data.drop(axis = 1,inplace = True)
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'对象没有属性'type'
AttributeError: 'numpy.ndarray' object has no attribute 'type'
我是个新手,由于某种原因,我无法获得for循环,而if语句逻辑一直困扰我.
I am a newb and for some reason I can't get the for loop and if statement logic to stick in my head.
推荐答案
You can use select_dtypes
to exclude columns of a particular type.
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)
这篇关于如何基于dtype删除DataFrame列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!