1

I am trying to create a new column Trend by writing this code

df_cal['Trend'] = np.where((df_cal['75% Quantile'] > df_cal['Shift 75% Quantile']) & (df_cal['25% Quantile'] > df_cal['Shift 25% Quantile']), "Up", 
                   np.where(df_cal['75% Quantile'] < df_cal['Shift 75% Quantile']) & (df_cal['25% Quantile'] < df_cal['Shift 25% Quantile']), "Down","Flat")

However when I run the code it give me this error

ValueError: setting an array element with a sequence.

Is there anyway to solve this?

A sample of the table is shown below.

        DateTime        75% Quantile    25% Quantile    Shift 75% Quantile  Shift 25% Quantile
0   2020-12-18 15:00    2.0             -4.0            NaN                 NaN
1   2020-12-18 16:00    4.0             -4.0            2.0                 -4.0
2   2020-12-18 17:00    -4.0            -10.0           4.0                 -4.0
3   2020-12-18 18:00    8.0             8.0             -4.0                -10.0
4   2020-12-18 19:00    0.0             -4.0            8.0                 8.0
5   2020-12-18 20:00    0.0             0.0             0.0                 -4.0
6   2020-12-19 08:00    8.0             8.0             0.0                 0.0
7   2020-12-19 09:00    -2.0            -6.0            8.0                 8.0
8   2020-12-19 10:00    4.0             -8.0            -2.0                -6.0
9   2020-12-19 11:00    0.0             -4.0            4.0                 -8.0
10  2020-12-19 12:00    4.0             -4.0            0.0                 -4.0
DDM
  • 303
  • 4
  • 19
  • Does this answer your question? [ValueError: setting an array element with a sequence](https://stackoverflow.com/questions/4674473/valueerror-setting-an-array-element-with-a-sequence) – Rabindra Mar 24 '21 at 03:55
  • Not really. I am just looking for an alternative method to achieve the same desired results as above. – DDM Mar 24 '21 at 04:52

1 Answers1

0

Explanation

I use pandas.mask() to achieve the conversion you need

Source Code

up_cond = (df_cal['75% Quantile'] > df_cal['Shift 75% Quantile']) 
& (df_cal['25% Quantile'] > df_cal['Shift 25% Quantile'])

down_cond = (df_cal['75% Quantile'] < df_cal['Shift 75% Quantile']) 
& (df_cal['25% Quantile'] < df_cal['Shift 25% Quantile'])

df_cal['Trend'] = 'Flat'
df_cal['Trend'] = df_cal['Trend'].mask(up_cond, "Up")                                
df_cal['Trend'] = df_cal['Trend'].mask(down_cond, "Down")

Result

enter image description here