0
$\begingroup$

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?

$\endgroup$
  • $\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 '18 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$ – subash poudel Oct 25 '18 at 3:45
1
$\begingroup$

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)

shuffle(a)

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.loc[df[df['item'].mask(
        ~df.item.isin(mapping[k])).notnull()].index.tolist(), 'category'] = k
| improve this answer | |
$\endgroup$
  • $\begingroup$ As commented & illustrated by @dustin, using dictionaries can easily get this done. $\endgroup$ – Random Nerd Nov 27 '18 at 9:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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