栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

快速删除只有一个不同值的数据框列

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

快速删除只有一个不同值的数据框列

您可以使用

Series.unique()
method找出一列中所有唯一的元素,对于
.unique()
仅返回
1
元素的列,可以将其删除。范例-

for col in df.columns:    if len(df[col].unique()) == 1:        df.drop(col,inplace=True,axis=1)

一种不就地删除的方法-

res = dffor col in df.columns:    if len(df[col].unique()) == 1:        res = res.drop(col,axis=1)

演示-

In [154]: df = pd.Dataframe([[1,2,3],[1,3,3],[1,2,3]])In [155]: for col in df.columns:   .....:     if len(df[col].unique()) == 1:   .....:         df.drop(col,inplace=True,axis=1)   .....:In [156]: dfOut[156]:   10  21  32  2

计时结果-

In [166]: %pastedef func1(df):        res = df        for col in df.columns:     if len(df[col].unique()) == 1:  res = res.drop(col,axis=1)        return res## -- End pasted text --In [172]: df = pd.Dataframe({'a':1, 'b':np.arange(5), 'c':[0,0,2,2,2]})In [178]: %timeit func1(df)1000 loops, best of 3: 1.05 ms per loopIn [180]: %timeit df[df.apply(pd.Series.value_counts).dropna(thresh=2, axis=1).columns]100 loops, best of 3: 8.81 ms per loopIn [181]: %timeit df.apply(pd.Series.value_counts).dropna(thresh=2, axis=1)100 loops, best of 3: 5.81 ms per loop

最快的方法似乎仍然是使用

unique
和遍历各列的方法。



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/645167.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号