i have a dataframe like thisenter image description here

i want to add new column and my desire format is like thisenter image description here

i use indexing eg dll.loc[:6,'category'] = "sectowise" dll.loc[7:11,'category'] = "productwise" dll.loc[12:16,'category'] = "collateral wise" but which is risky because data index can change anytime is there any method to do this?

  • $\begingroup$ How about use a dictionary that maps items to categories and populate the new column based on the dictionary key values. $\endgroup$
    – dustin
    Oct 24, 2018 at 17:15
  • $\begingroup$ rows of dataset is large so how can i use dictionary key values ? can u give me example to solve this problem? $\endgroup$ Oct 25, 2018 at 3:45

1 Answer 1


Here is an example (I just through it together hastily). You can probably do this a little bit smoother.

import pandas as pd
import numpy as np
from random import shuffle

a = np.repeat(['a', 'b', 'c', 'd', 'e'], 6)
x = np.random.randn(30)
y = np.random.randn(30)
z = np.random.randn(30)


a = a.reshape(30, 1)
x = x.reshape(30, 1)
y = y.reshape(30, 1)
z = z.reshape(30, 1)

data = np.concatenate((a, x, y, z), axis=1)
df = pd.DataFrame(data, columns=['item', 'x', 'y', 'z'])

mapping = {'1': ['a', 'b'], '2': ['d'], '3': ['c', 'e']}

for k in mapping:
        ~df.item.isin(mapping[k])).notnull()].index.tolist(), 'category'] = k
  • $\begingroup$ As commented & illustrated by @dustin, using dictionaries can easily get this done. $\endgroup$ Nov 27, 2018 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.