Better way to create new pandas comparison dataframe

2094 views python-3.x

I have three dataframes of the same size. I'm wondering if there's a more concise and/or efficient way to create a new dataframe again of the same size, whereby the values are set according to comparisons of the original dataframes. For example:

Original three dataframes: close, low, high

long_short = pd.DataFrame().reindex_like(close)
long_short[:] = 0
long_short = long_short.astype(np.int64)
long_short[close < low] = -1
long_short[close > high] = 1

answered question

What does reindex_like() achieve on empty dataframe?

Just copying the size and header of the close df

You can vectorise a function of three dataframes to create a new df based on close, low, high as in….

1 Answer


It would be nice to have a sample of the data to be sure.

How about just doing the comparison and then converting the booleans to 0/1 values?

negative_values = (close < low).astype(int)
positive_values = (close > high).astype(int)

long_short = positive_values - negative_values

posted this

Have an answer?


Please login first before posting an answer.