Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 使用Pandas和socket.gethostbyname填充数据帧缺少的IP地址_Python 3.x_Sockets_Pandas - Fatal编程技术网

Python 3.x 使用Pandas和socket.gethostbyname填充数据帧缺少的IP地址

Python 3.x 使用Pandas和socket.gethostbyname填充数据帧缺少的IP地址,python-3.x,sockets,pandas,Python 3.x,Sockets,Pandas,我最近才开始使用熊猫。我试图通过使用sockets.gethostbtname解析主机名来填充IP地址列 下面是一个名为data的示例数据帧 domain ip_address 0 google.com NaN 1 yahoo.com NaN 我有以下代码: data.ip_address = data['ip_address'].fillna(socket.gethostbyname(data.iloc[data.ind

我最近才开始使用熊猫。我试图通过使用sockets.gethostbtname解析主机名来填充IP地址列

下面是一个名为data的示例数据帧

      domain      ip_address
0   google.com           NaN
1   yahoo.com           NaN
我有以下代码:

data.ip_address =  data['ip_address'].fillna(socket.gethostbyname(data.iloc[data.index]['domain']))
但我得到的错误如下:

TypeError: gethostbyname() argument 1 must be str, bytes or bytearray, not Series

出现错误的原因是socket.gethostbyname函数需要字符串或字节字符串,但输入是一个序列。 每当我们对数据帧执行非迭代操作时,它们都会在一系列数据上进行内部迭代。 因此,这里提取一个序列,并将该序列作为参数传递给socket.gethostbyname

因此,这里我们可以使用map来解决这个问题:

import socket
import pandas as pd
# Creating a dataframe with your input
data_in = [{'domain': 'google.com', 'ip_address': None},
 {'domain': 'yahoo.com', 'ip_address': None}]
df = pd.DataFrame(data_in)
df['ip_address'] = df['domain'].map(lambda host:socket.gethostbyname(host))
现在,这个df2将如下所示

       domain      ip_address
0  google.com  172.217.26.174
1   yahoo.com  98.139.180.149
只有当所有主机名都有效时,上述主机名到ip的解析才有效。假设,如果您有任何不可解析的主机名,比如test1989,那么这将失败,并且数据帧不会被更改