I have a dataframe similar to the following:
df:
ip last_active
192.167.0.9 01/02/2012
226.90.2.12 05/06/2013
10.90.2.09 05/06/2014
12.60.2.80
192.168.2.11-17 05/06/2016
Is there a way to expand the ip address from last row in the df? A perfect solution would be:
df:
ip last_active
192.167.0.9 01/02/2012
226.90.2.12 05/06/2013
10.90.2.09 05/06/2014
12.60.2.80
192.168.2.11 05/06/2016
192.168.2.12 05/06/2016
192.168.2.13 05/06/2016
192.168.2.14 05/06/2016
192.168.2.15 05/06/2016
192.168.2.16 05/06/2016
192.168.2.17 05/06/2016
Any guidance is appreciated!
You can apply a function to make a list of the IPs in the range elements, then use explode()
if you have a recent pandas version
def ip_splitter(ip):
if '-' in ip:
last_octet_range=[int(i) for i in ip.split('.')[3].split('-')]
new_ips = [i for i in range(last_octet_range[0],last_octet_range[1]+1)]
expanded_range = ['.'.join(ip.split('.')[:3]+[str(i)]) for i in new_ips]
return expanded_range
return ip
df['ip']=df['ip'].apply(ip_splitter)
df
ip last_active
0 192.167.0.9 01/02/2012
1 226.90.2.12 05/06/2013
2 10.90.2.09 05/06/2014
3 12.60.2.80 None
4 [192.168.2.11, 192.168.2.12, 192.168.2.13, 192... 05/06/2016
df.explode('ip')
ip last_active
0 192.167.0.9 01/02/2012
1 226.90.2.12 05/06/2013
2 10.90.2.09 05/06/2014
3 12.60.2.80 None
4 192.168.2.11 05/06/2016
4 192.168.2.12 05/06/2016
4 192.168.2.13 05/06/2016
4 192.168.2.14 05/06/2016
4 192.168.2.15 05/06/2016
4 192.168.2.16 05/06/2016
4 192.168.2.17 05/06/2016