pythonpandasdataframe

How to insert a column at a specific index with values for some rows in a single operation?


I want to insert a column at a specific index in a Pandas DataFrame, but only assign values to certain rows. Currently, I am doing it in two steps:

df = pd.DataFrame({'A': [1, 2, 3, 4, 5],
                  'B': [10, 20, 30, 40, 50] })
df.insert(1, 'NewCol', None)
df.loc[[1, 3], 'NewCol'] = ['X', 'Y']

Is there a more concise way to achieve this in a single operation?


Solution

  • Provide a Series with the correct indices to insert:

    df.insert(1, 'NewCol', pd.Series(['X', 'Y'], index=[1, 3]))
    

    Output:

       A NewCol   B
    0  1    NaN  10
    1  2      X  20
    2  3    NaN  30
    3  4      Y  40
    4  5    NaN  50