3 回答

TA貢獻(xiàn)1821條經(jīng)驗(yàn) 獲得超6個(gè)贊
當(dāng)您這樣做時(shí),len(df['column name'])您只會得到一個(gè)數(shù)字,即DataFrame中的行數(shù)(即列本身的長度)。如果要應(yīng)用于len列中的每個(gè)元素,請使用df['column name'].map(len)。所以嘗試
df[df['column name'].map(len) < 2]

TA貢獻(xiàn)1951條經(jīng)驗(yàn) 獲得超3個(gè)贊
要直接回答該問題的原始標(biāo)題“如何基于條件表達(dá)式從pandas DataFrame中刪除行”(我理解這不一定是OP的問題,但可以幫助其他用戶解決此問題),一種方法是使用該降的方法:
df = df.drop(some labels)
df = df.drop(df[<some boolean condition>].index)
例
要?jiǎng)h除列“得分”小于50的所有行:
df = df.drop(df[df.score < 50].index)
就地版本(如注釋中所指出)
df.drop(df[df.score < 50].index, inplace=True)
多種條件
(請參閱布爾索引)
運(yùn)算符是:|for or,&for and和~for not。這些必須使用括號進(jìn)行分組。
刪除列“得分”小于50和大于20的所有行
df = df.drop(df[(df.score < 50) & (df.score > 20)].index)
添加回答
舉報(bào)