我需要清理我的数据框并删除所有没有数字数据的列。我的列被归类为“对象”,有些列标记为 int/float,但主要包含 NaN。我只想保留充满数字的列。有什么办法吗?
最佳答案
使用select_dtypes
并传递 np.number
以仅过滤数字类型:
In [69]:
df = pd.DataFrame({'int':np.arange(5), 'float':np.random.randn(5), 'str':list('abcde')})
df
Out[69]:
float int str
0 0.987218 0 a
1 0.336119 1 b
2 1.800194 2 c
3 4.566850 3 d
4 -0.306808 4 e
In [71]:
df.select_dtypes([np.number])
Out[71]:
float int
0 0.987218 0
1 0.336119 1
2 1.800194 2
3 4.566850 3
4 -0.306808 4
这接受 numpy type hierarchy 中的任何类型
要删除包含任何 NaN
的列,您可以调用 dropna(axis=1)
感谢@Leb
关于python - Pandas : dropping multiple columns and keeping only ones with numeric data,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33503754/