首页 > 解决方案 > Recode/concatenate multiple values python

问题描述

I have a df that I wish to perform some recoding on, and I'm not sure what is the best approach.

For values from 1 to 9, I need to add 5900 to the number (so for 1, it would be 59001). For values from 10 to 99, I need to add 590 to the number For values from 100 to 175, I need to add 59 to the number

Is there a way to automate this process, instead of manually recoding?

I have the following, but it returns an error


def recode(df):
    for n, i in enumerate(list(df)):
        for num in range(0,10):
            if i == num: df[n] = int(str(5900) + str(i))

        for num in range(10,100):
            if i == num: df[n] = int(str(590) + str(i))

        for num in range(100,200):
            if i == num: df[n] = int(str(59) + str(i))
    return(list)

df['col'] = df['col'].apply(recode_fips_ohio)

Returns error: TypeError: 'int' object is not iterable

标签: pythonnumpyrecode

解决方案


You need only one line of code:

df += 59000

推荐阅读