如何根據條件表達式有效地從 Pandas DataFrame 中刪除行?

DDD
發布: 2024-11-15 11:55:03
原創
589 人瀏覽過

How to Effectively Remove Rows from Pandas DataFrames Based on Conditional Expressions?

Conditional Row Removal in Pandas DataFrames

Encountering the "KeyError: u'no item named False'" error when attempting to remove rows from a pandas DataFrame using the expression "df[(len(df['column name']) < 2)]" indicates an incorrect approach.

To directly address the issue of deleting rows based on a conditional expression, there are several methods available in pandas. One effective technique involves employing the drop() method:

df = df.drop(some_labels)
df = df.drop(df[<boolean condition>].index)</p>
<p><strong>Example:</strong></p>
<p>Consider a DataFrame with a 'score' column. To remove all rows where the score is below 50:</p>
<pre class="brush:php;toolbar:false">df = df.drop(df[df.score < 50].index)
登入後複製

For in-place deletion:

df.drop(df[df.score < 50].index, inplace=True)
登入後複製

Multiple Conditions:

Using Boolean indexing, it is possible to combine multiple conditions for row removal. For instance, to delete rows where 'score' is both below 50 and above 20:

df = df.drop(df[(df.score < 50) & (df.score > 20)].index)
登入後複製

By applying these conditional removal methods, it is straightforward to remove rows from pandas DataFrames based on specified criteria.

以上是如何根據條件表達式有效地從 Pandas DataFrame 中刪除行?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板