Issue
I have a list as below in python. In this list, the numbers are equal in some cases, but in cases where the numbers are equal, I want to print the value in the previous inequality in the 'c' column.
conditions = [ df[a] > df[b], (df[a] == df[b]), df[a] < df[b] ]
choices = [ "A bigger than B", 'same', 'B bigger than A' ]
df["c"] = np.select(conditions, choices, default=np.nan)
A | B | C |
---|---|---|
1 | 2 | B bigger than A |
2 | 2 | same |
2 | 2 | same |
3 | 2 | A bigger than B |
3 | 3 | same |
3 | 3 | same |
3 | 6 | B bigger than A |
i want to do
A | B | C |
---|---|---|
1 | 2 | B bigger than A |
2 | 2 | B bigger than A |
2 | 2 | B bigger than A |
3 | 2 | A bigger than B |
3 | 3 | A bigger than B |
3 | 3 | A bigger than B |
3 | 6 | B bigger than A |
Solution
If values are equal, use previous
as the comment. Otherwise, set comment
conditionally.
previous = "same"
for i in range(len(df)):
if df.loc[i,"A"] == df.loc[i,"B"]:
comment = previous
else:
comment = "A bigger than B" if df.loc[i,"A"] > df.loc[i,"B"] else "B bigger than A"
df.loc[i,"C"] = comment
previous = comment
Result
A B C
0 3 1 A bigger than B
1 1 2 B bigger than A
2 3 1 A bigger than B
3 1 1 A bigger than B
4 1 3 B bigger than A
Answered By - Sruthi
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.