我正在尋找一種更Pythonic(并且更快?。┑姆椒▉砬宄魏涡兄芯哂腥齻€字符串之一的任何行。我的代碼可以工作,但是太慢了!任何建議,將不勝感激!# Check out each rowfor i,row in df2.iterrows(): for index in range(df2.shape[1]): # Check out values in each column # if it's 98 or 99, drop it if df2.iloc[i,index] == '98.00': df2.drop(i) print('dropped row ', i, ' due to high value') elif df2.iloc[i,index] == '99.00': df2.drop(i) print('dropped row ', i, ' due to high value') # or if the value is the default text null value, drop it elif df2.iloc[i,index] == '#NULL!': df2.drop(i) print('dropped row ', i, 'due to null value')
4 回答

呼啦一陣風
TA貢獻1802條經驗 獲得超6個贊
我有點困惑,但您可以使用帶有 |(或)的過濾器來存儲要刪除的行,然后在 df 上使用 drop 。
例如:
drop_row = df.loc[(df['some_column] > 某事) | (df['some_column] > 某事)
df.drop(index = drop_row.index, inplace = True)

瀟湘沐
TA貢獻1816條經驗 獲得超6個贊
isin
結合any
應該工作:
df = df[~df.isin(["98.0", "99.0", "#NULL!"]).any(axis="columns")]

冉冉說
TA貢獻1877條經驗 獲得超1個贊
如果您想使用 drop() 和 isin() 函數(之前建議),我建議:
df.drop(index=df[df.isin(["98.00", "99.00", "#NULL!"]).any(1)].index, inplace=True)
這是一種更簡短的表達方式:
df.drop(index=df[((df == "98.00") | (df == "99.00") | (df == '#NULL!')).any(1)].index, inplace=True)
下面描述一下代碼的工作原理:
首先選擇驗證任何請求條件的索引。
然后,在 drop 函數中使用選擇的索引來刪除數據框中的相關行。
要永久執行 df 中的放置,需要“inplace=True”。如果您只想將放置結果顯示為臨時(例如通過 print() 函數),則可以替換為“inplace=False”。
添加回答
舉報
0/150
提交
取消