I am trying to perform np.where
function on a dataframe starting from row 20 onward. The code that I entered as follow:
df['buy'] = np.where((df.iloc[20:,]['signal']==1), 'buy','no buy')
It showed the error below: ValueError: Length of values (226) does not match length of index (246)
Anyone know how to fix it please?
I want pandas to return value from row 20 onward.
CodePudding user response:
This is an assignment error, df
has 246 entries, but you are trying to assign a numpy vector with 226 values to it.
What do you intend the result should be?
you could subset the dataframe?
df_sub = df.iloc[20:].copy()
df_sub['buy']=np.where((df_sub.iloc['signal']==1), 'buy','no buy')
CodePudding user response:
IIUC, you could use "mixed" indexing for the assignment:
n = df.columns.get_loc('buy')
df.iloc[20:, n] = np.where((df.iloc[20:,]['signal']==1), 'buy','no buy')