Search code examples
pandasadditionip-address

Increment IP address by 1 depending on value of subnet (on different column)


I have this DF, composed of ipaddress type objects.

        subnet
0  10.204.26.0
1  10.204.26.0
2  10.204.26.0
3  10.204.30.0
4  10.204.30.0
5  10.204.30.0
6  10.204.30.0
7  10.204.30.0
8  10.204.30.0
9  10.204.30.0

I want to create a new column, say df['ip'] which will increment on the subnet (and/or previous row) to get a different address on each different row, but taking into account that the subnets do differ.

If the subnet is only one, the problem is easily solved by doing df['ip'] = df.index + df[subnet] + 1. That would produce something like this:

        subred            ip
0  10.204.26.0   10.204.26.1
1  10.204.26.0   10.204.26.2
2  10.204.26.0   10.204.26.3

But since the subnets are likely to be more than one, then the expected result would be:

        subred            ip
0  10.204.26.0   10.204.26.1
1  10.204.26.0   10.204.26.2
2  10.204.26.0   10.204.26.3
3  10.204.30.0   10.204.30.1
4  10.204.30.0   10.204.30.2
5  10.204.30.0   10.204.30.3
6  10.204.30.0   10.204.30.4
7  10.204.30.0   10.204.30.5
8  10.204.30.0   10.204.30.6
9  10.204.30.0   10.204.30.7

How to achieve this?

Thanks!


Solution

  • Try this.

    df['ip']= df['subnet'].str[:10]+ (df.groupby('subnet').cumcount()+1).astype(str)
    df
    

    output

             subnet     ip
    0   10.204.26.0     10.204.26.1
    1   10.204.26.0     10.204.26.2
    2   10.204.26.0     10.204.26.3
    3   10.204.30.0     10.204.30.1
    4   10.204.30.0     10.204.30.2
    5   10.204.30.0     10.204.30.3
    6   10.204.30.0     10.204.30.4
    7   10.204.30.0     10.204.30.5
    8   10.204.30.0     10.204.30.6
    9   10.204.30.0     10.204.30.7