1

I'm trying to create a class column in a pandas dataframe conditional another columns values. The value will be 1 if the other column's i+1 value is greater than the i value and 0 otherwise.

For example:

column1 column2
   5       1
   6       0
   3       0
   2       1
   4       0

How do create column2 by iterating through column1?

0

2 Answers 2

3

You can use the diff method on the first column with a period of -1, then check if it is less than zero to create the second column.

import pandas as pd

df = pd.DataFrame({'c1': [5,6,3,2,4]})
df['c2'] = (df.c1.diff(-1) < 0).astype(int)

df
# returns:
   c1  c2
0   5   1
1   6   0
2   3   0
3   2   1
4   4   0
Sign up to request clarification or add additional context in comments.

Comments

0

You can also use shift. Performance is almost the same as diff but diff seems to be faster by a a little.

df = pd.DataFrame({'column1': [5,6,3,2,4]})
df['column2'] = (df['column1'] <df['column1'].shift(-1)).astype(int)
print(df)
   column1  column2
0        5        1
1        6        0
2        3        0
3        2        1
4        4        0

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.