Home > Blockchain >  How can I increase the efficiency of my loop that replaces values?
How can I increase the efficiency of my loop that replaces values?

Time:08-04

def assignGroup(row):
    if row['democ_bad']== 1:
        return 4
    elif row['democ_bad'] == 2:
        return 3
    elif row['democ_bad'] == 3:
        return 2
    elif row['democ_bad'] == 4:
        return 1
    else:
        return np.nan

wvs['demo_better']=wvs.apply(assignGroup,axis=1)

CodePudding user response:

You could use Pandas' functionality for categorical data:

from pandas.api.types import CategoricalDtype

cat_type = CategoricalDtype(range(1, 5))

wvs['demo_better'] = wvs['democ_bad'].astype(cat_type)

CodePudding user response:

Try this.

mapping = {1: 4, 2: 3, 3: 2, 4: 1}
wvs['demo_better'] = wvs['democ_bad'].map(mapping)

It should return nans when there is no mapping.

  • Related