[英]Removing pandas rows based on existence of values in certain columns
我有一個像這樣的df:
A B C
f s x
a b c
n
p l k
i
s j p
現在,我想刪除 df 列的 rest 上 A 列中具有值但為空的所有記錄,我該如何實現呢? 預期的結果將是一個像這樣的df:
A B C
f s x
a b c
p l k
s j p
使用DataFrame.replace
將空白設置為 NaN,然后您可以使用DataFrame.dropna
刪除帶有 NaN 的行:
df.replace(r'^\s*$', np.nan, regex=True).dropna()
或者,如果您只想在 A 列不是 NaN 時刪除
df.replace(r'^\s*$', np.nan, regex=True)
.loc[lambda x: ~(x['A'].notna()
& x.filter(regex='!A').isna().all(axis=1))]
#morgan equivalent
#df.replace(r'^\s*$', np.nan, regex=True)
# .loc[lambda x: x['A'].isna()
# | x.filter(regex='!A').notna().any(axis=1)]
如果您在 B/C 中有空 (NaN) 單元格,則一個簡單的dropna
將起作用:
df.dropna()
否則,使用 boolean 索引:
df[df.ne('').all(1)]
output:
A B C
0 f s x
1 a b c
3 p l k
5 s j p
筆記
盡管我懷疑您是否想要這個,但如果您只想在 A 不是''
時刪除行,請添加第二個條件:
df[df['A'].eq('')|df.ne('').all(1)]
示例輸入:
df = pd.DataFrame({'A': ['x', '', '', 'x', '', 'x'],
'B': ['x', 'x', '', 'x', '', ''],
'C': ['x', 'x', 'x', '', '', '']})
A B C
0 x x x
1 x x
2 x
3 x x
4
5 x
output:
A B C
0 x x x
1 x x
2 x
4
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.