pythonpandasnumpyalternate

pandas: fill empty column with alternate values


I have a dataframe as follows, but with more rows

import pandas as pd
import numpy as np

d = {'col1': ['data1', 'data2','data3','data4','data5'], 
         'col2': ['a', 'b','c','d','e']}
df = pd.DataFrame(data=d)

I have added an empty column to this dataframe

df['type']= ' '

now I would like to fill in the empty column with alternate values. so if the index is even, then i would like to add 'type_a' and if the index is odd, i would like to add 'type_b'.

I did the following

df['type'] = np.where(df.iloc[::2,::2], 'type_a', 'type_b') 

however the index does not match and i get the following error:

ValueError: Length of values does not match length of index

Solution

  • try:

    df['type']=np.where(df.index%2==0, 'type_a', 'type_b') 
    

    output of df:

        col1    col2    type
    0   data1   a       type_a
    1   data2   b       type_b
    2   data3   c       type_a
    3   data4   d       type_b
    4   data5   e       type_a