我有一个pandas DataFrame,我想从中删除行,其中特定列中字符串的长度大于2。我希望能够做到这一点(根据此答案):df[(len(df['column name']) < 2)]但我只是得到错误:KeyError: u'no item named False'我究竟做错了什么?(注意:我知道我可以df.dropna()用来删除包含any的行NaN,但是我没有看到如何根据条件表达式删除行。)
3 回答

达令说
TA贡献1821条经验 获得超6个赞
当您这样做时,len(df['column name'])您只会得到一个数字,即DataFrame中的行数(即列本身的长度)。如果要应用于len列中的每个元素,请使用df['column name'].map(len)。所以尝试
df[df['column name'].map(len) < 2]

饮歌长啸
TA贡献1951条经验 获得超3个赞
要直接回答该问题的原始标题“如何基于条件表达式从pandas DataFrame中删除行”(我理解这不一定是OP的问题,但可以帮助其他用户解决此问题),一种方法是使用该降的方法:
df = df.drop(some labels)
df = df.drop(df[<some boolean condition>].index)
例
要删除列“得分”小于50的所有行:
df = df.drop(df[df.score < 50].index)
就地版本(如注释中所指出)
df.drop(df[df.score < 50].index, inplace=True)
多种条件
(请参阅布尔索引)
运算符是:|for or,&for and和~for not。这些必须使用括号进行分组。
删除列“得分”小于50和大于20的所有行
df = df.drop(df[(df.score < 50) & (df.score > 20)].index)
添加回答
举报
0/150
提交
取消