I have a dataframe containing 7 columns and I want to simultaneously loop through two of them to compare the values in each row. This is my for loop header, where watchCol and diaryCol are column numbers:
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)
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.
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.