[譯]如何根據條件從pandas DataFrame中刪除不需要的行?


問題來源:https://stackoverflow.com/questions/13851535/how-to-delete-rows-from-a-pandas-dataframe-based-on-a-conditional-expression

問:
我有一個pandas DataFrame,我想刪除它特定列中字符串差姑娘是大於2的行,我知道我可以使用df.dropna()來去除包含NaN的行,但我沒有找到如何根據條件刪除行。
似乎我能夠這樣做:

df[(len(df['column name']) < 2)]

但卻報錯了:
KeyError: u'no item named False'
誰能告訴我錯在哪里了?

回答一:
當你這樣做時,len(df['column name'])你只得到一個數字,即DataFrame中的行數(即列本身的長度)。如果要應用於len列中的每個元素,請使用df['column name'].map(len)。
嘗試使用:

df[df['column name'].map(len) < 2]

評論:
我想出了一種使用列表解析的方法:df[[(len(x) < 2) for x in df['column name']]] 但是你這種方法更好些。

回答二:
要直接回答這個問題,一種方法是使用drop方法:

df = df.drop(some labels)
df = df.drop(df[<some boolean condition>].index)

要刪除列“score”<50的所有行:

df = df.drop(df[df.score < 50].index)

替換版本

df.drop(df[df.score < 50].index, inplace=True)

多條件情況:
可以使用操作符: | 只需其中一個成立, & 同時成立, ~ 表示取反,它們要用括號括起來。
例如刪除列“score<50 和>20的所有行

df = df.drop(df[(df.score < 50) & (df.score > 20)].index)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM