'Assignment with pandas iloc where RHS length is shorter than LHS
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.
Solution 1:[1]
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')
Solution 2:[2]
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')
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | distracted-biologist |
| Solution 2 | mozway |
