Setting a selection of rows equal to a list of strings

Viewed 274

I have a dataframe and I want to input to a slice of rows in a specific columns, where the input is a list of strings - so in each of the selected rows, I want the same list of strings.

But when I try this, I get an error:

df['col'].iloc[0:460] = ['x', 'y', 'z', 'q']

ValueError: cannot set using a slice indexer with a different length than the value

It works fine when I do the same but instead of a list of strings I just have a single string. Why won't it accept a list as input?

2 Answers

We can try update, chain of iloc with [] columns is not recommended

df.update(pd.DataFrame({'col':[['x', 'y', 'z', 'q'] for x in range(0,460)]},index=df.index[:460]))

Notice I create the list by for loop, due to you do not want same copy for each row, if same object then change each of the value in the list , all other row will change as well.

Use get_indexer and only with iloc

df.iloc[0:460, df.columns.get_indexer(['col'])[0]]=[['x', 'y', 'z', 'q'] for x in range(0,460)]

It does not work because pandas interpret list type as a list of value (i.e a multiple line elements)

If you duplicate your list for the number of occurrence that you need to replace it will work:

df = pd.DataFrame({'col':['a','b','c','d','e']})

df['col'].iloc[0:5] = [['x', 'y', 'z', ]]*5
print(df)

that returns

         col
0  [x, y, z]
1  [x, y, z]
2  [x, y, z]
3  [x, y, z]
4  [x, y, z]
Related