TransWikia.com

Getting "cannot set using a multi-index selection indexer with a different length than the value" error while using np.where function

Stack Overflow Asked by ashok747 on December 7, 2020

I am trying to append two data frames row wise iteratively. After that I am trying fill 0 values in one column with the values in other columns and vice versa. I am using np.where function to fill the 0 values. When I am doing it separately it is giving correct result but when I am using it in a loop it is throwing "cannot set using a multi-index selection indexer with a different length than the value" error. My code looks like below.

def myfunc(dd1,dd2,dfc):
n=dd1.shape[0]
for i in range(n):
    dfc2=dd1.iloc[i:i+1].append(dd2.iloc[i:i+1])
    dfc=dfc.append(dfc2)
m=dfc.shape[0]
for j in range(m):
    dfc.iloc[j:j+1,2:3]=np.where(dfc.iloc[j:j+1,2:3]==0,dfc.iloc[j+1:j+2,3:4],dfc.iloc[j:j+1,2:3])
    dfc.iloc[j+1:j+2,3:4]=np.where(dfc.iloc[j+1:j+2,3:4]==0,dfc.iloc[j:j+1,2:3],dfc.iloc[j+1:j+2,3:4])
return dfc

Where dd1 and dd2 are my dataframes, I am appending rows in them iteratively to a empty dataframe dfc. Here I am using row and column indices to fill the values. Any help on this will be appreciated.

One Answer

This is not how np.where works. The input of np.where is a list-like object. Instead of looping every data in the dataframe and fed it into the np.where, you should input the entire array to the np where.

dfc.iloc[:,2:3] = np.where(dfc.iloc[:,2:3]==0,dfc.iloc[:,3:4].shift(-1),dfc.iloc[:,2:3])
dfc.iloc[:,3:4] = np.where(dfc.iloc[:,3:4]==0,dfc.iloc[:,2:3],dfc.iloc[:,3:4].shift(-1))

This should work now. Be careful about the pd.DataFrame.iloc and avoid it if you are assigning it to new values. I would recommend you to use loc instead. My script may have potential bug depends on your pandas version.

Correct answer by Fergus Kwan on December 7, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP