简体   繁体   English

Python iterrows() 从 Dataframe 索引和删除行

[英]Python iterrows() to index and drop rows from Dataframe

I'm iterating over a df and want to drop rows based on a condition.我正在迭代 df 并希望根据条件删除行。 It's like to check the contents of a sting for a character and drop if it does not exist.这就像检查一个字符的字符串的内容,如果它不存在则丢弃。 I have tried the code below, with exceptions.我已经尝试了下面的代码,但有例外。 How can I access the third column's iterative row value and check for contains.如何访问第三列的迭代行值并检查包含。

for index, row in df_new.iterrows():
    if not row[2].contains(','):
        df_new.drop(index, inplace = True)

An exception is thrown:抛出异常:

AttributeError: 'str' object has no attribute 'contains' AttributeError: 'str' 对象没有属性 'contains'

I've tried a variety of string assignment also like:我已经尝试了各种字符串赋值,比如:

for index, row in df_new.iterrows():
    string = str(row[2])
    if not string.contains(','):
        df_new.drop(index, inplace = True)

做起来可能会更快。

df_new = df_new[~df_new.Column_name.str.contains(",")]

Use the in operator:使用in运算符:

for index, row in df_new.iterrows():
    if ',' not in str(row[2]):
        df_new.drop(index, inplace = True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM