简体   繁体   English

如何为每个循环遍历数据帧中的两列?

[英]How to for each loop through two columns in a dataframe?

I have a dataframe containing 7 columns and I want to simultaneously loop through two of them to compare the values in each row. 我有一个包含7列的数据框,我想同时遍历其中的两列以比较每一行中的值。 This is my for loop header, where watchCol and diaryCol are column numbers: 这是我的for循环标题,其中watchCol和diaryCol是列号:

for watch, diary in df.iloc[:, watchCol], df.iloc[:, diaryCol]:

When I run this, I get the following error on that line: 运行此命令时,在该行上出现以下错误:

ValueError: too many values to unpack (expected 2) ValueError:太多值无法解包(预期2)

What am I doing wrong? 我究竟做错了什么?

Thanks 谢谢

EDIT: 编辑:

Both columns contain datetimes. 两列均包含日期时间。 I need to compare the two values, and if the difference is within a certain range, I copy the value from the watchCol into another column, otherwise I move to the next row. 我需要比较两个值,如果差异在一定范围内,则将值从watchCol复制到另一列,否则移至下一行。

If you're trying to compare entries row by row, try this: 如果您要逐行比较条目,请尝试以下操作:

import pandas as pd  
df = pd.DataFrame({"a": [2, 2, 2, 2, 2], "b": [4, 3, 2, 1, 0]})

df["a greater than b"] = df.apply(lambda x: x.a > x.b, axis=1)
print df

   a  b a greater than b
0  2  4            False
1  2  3            False
2  2  2            False
3  2  1             True
4  2  0             True

That said, if you did want to loop through the elements row by row: 也就是说,如果您确实想逐行遍历元素:

for a, b in zip(df.iloc[:, 0], df.iloc[:, 1]):
    print a, b

2 4
2 3
2 2
2 1
2 0

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

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