我正在寻找一种更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 回答
![?](http://img1.sycdn.imooc.com/545862120001766302200220-100-100.jpg)
呼啦一阵风
TA贡献1802条经验 获得超6个赞
我有点困惑,但您可以使用带有 |(或)的过滤器来存储要删除的行,然后在 df 上使用 drop 。
例如:
drop_row = df.loc[(df['some_column] > 某事) | (df['some_column] > 某事)
df.drop(index = drop_row.index, inplace = True)
![?](http://img1.sycdn.imooc.com/5458689e000115c602200220-100-100.jpg)
潇湘沐
TA贡献1816条经验 获得超6个赞
isin
结合any
应该工作:
df = df[~df.isin(["98.0", "99.0", "#NULL!"]).any(axis="columns")]
![?](http://img1.sycdn.imooc.com/54584e1f0001bec502200220-100-100.jpg)
冉冉说
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
提交
取消