SM079
SM079

Reputation: 715

DataFrame: setting value based on column value

I have a df

ID   value 
=============
A    10
B    12
C    15
A    13
C    16

Is there a way to populate a Flag columns based on the condition value of A < B < C is true else false

ID   value   flag
==================
A    10      True
B    12      True
C    15      True
A    13      False
C    16      True

Upvotes: 0

Views: 56

Answers (1)

LearnerMantis
LearnerMantis

Reputation: 84

Since there is no explanation about the underlying data from you, I will make some assumptions based on your question and comments provided, so that it may benefit someone else too. To summarize your question, you want to check the numeric in the 'value' column for each row with the value in the previous row and if the current row value is greater than the value in the previous row, you would want to place a boolean flag with True or else False against the current row. Based on your comment, I assume that the ID column does not have any role in determining the value in the 'flag' column. This means that no groupby is needed. Based on the above assumptions, following is my solution.

# create another DataFrame with rows shifted one position up from the original
# dataframe df

df_shifted = df.shift(-1)

# Create a series by comparing the shifted dataframe 'value' column with
# 'value' column in the original dataframe.
# This is done to compare current row with previous row.

flag_series = (df_shifted['value'] > df['value'])

# Then shift the series back so that it aligns with the original dataframe

flag_series = flag_series.shift(1)

# Now create a column named 'flag' in the original dataframe and assign 
# the series of flags

df = df.assign(flag=flag_series)

# Finally assign the flag to true for the first row of the dataframe
# as there are no rows before it to compare

df.iloc[0, 2] = True

Please note you can compact the code further. I have written the code in an elaborate manner so that it is easier to understand.

Upvotes: 1

Related Questions