pandas 循环遍历列并在特定条件下停止(python)

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/46456735/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 04:32:33  来源:igfitidea点击:

Loop through column and stop at a certain condition (python)

pythonpandasconditional-statementsrowscontinue

提问by Erin

I have a dataframe similar to below,

我有一个类似于下面的数据框,

Date            A  B
2017-01-01      1  1
2017-01-02      2  2
2017-01-03      1  2

For each column, I want to test the condition A==B for each name in the groupby statement. If this condition does not hold true, I want to print "Condition ends at 2017-01-03." I'm not sure how to loop through each row in this dataframe. I'm envisioning something like this code, although I know I am not itterating through the correct thing:

对于每一列,我想测试 groupby 语句中每个名称的条件 A==B。如果此条件不成立,我想打印“条件结束于 2017-01-03”。我不确定如何遍历此数据框中的每一行。我正在设想类似这样的代码,尽管我知道我没有通过正确的事情进行迭代:

for i in df.Date:
    if df.A == df.B:
        continue
    if df.A != df.B:
        print ("Condition ends at", i)

回答by zillaofthegods

Please take a look at this.

请看看这个

You would be iterating through each row and then accessing the appropriate column as a key, in this way you can compare column to each other in each row

您将遍历每一行,然后访问适当的列作为键,这样您就可以将每一行中的列相互比较

回答by Evan Nowak

You could do it like this:

你可以这样做:

print 'Condition ends at', (df.A.values != df.B.values).argmax()

回答by maor10

You could use the nice pythonic syntax:

您可以使用漂亮的 pythonic 语法:

print next([d for d in dates if d.A != d.B], None)

The None would be the default value if none is found

如果没有找到,则 None 将是默认值