Assigning a numeric label to rows according to their proximity to the preceding row's value

0
0

Here’s an example code in Python that assigns a numeric label to each row of a DataFrame based on its proximity to the preceding row’s value:

import pandas as pd

# create a sample DataFrame
df = pd.DataFrame({‘value’: [10, 15, 8, 18, 20, 12, 25]})

# initialize the label column with None values
df[‘label’] = None

# assign labels based on proximity to the preceding row’s value
for i in range(1, len(df)):
if df[‘value’][i] > df[‘value’][i-1]:
df.at[i, ‘label’] = 1
elif df[‘value’][i] < df[‘value’][i-1]:
df.at[i, ‘label’] = -1
else:
df.at[i, ‘label’] = 0

print(df)

OUTPUT

value label
0 10 None
1 15 1
2 8 -1
3 18 1
4 20 1
5 12 -1
6 25 1

  • You must to post comments
Showing 0 results
Your Answer

Please first to submit.