python - api查询的pandas df

标签 python pandas

我在一个 ip 地址的 JSON 中有如下所示的 API 数据。典型查询包含 50 个 ip 设备。

[{'ip': '11.22.33.44',
  'services': [{'port': 80,
    'service_name': 'HTTP',
    'transport_protocol': 'TCP'},
   {'port': 1911, 'service_name': 'FOX', 'transport_protocol': 'TCP'},
   {'port': 3011, 'service_name': 'HTTP', 'transport_protocol': 'TCP'},
   {'port': 5011,
    'service_name': 'HTTP',
    'certificate': 'thisisgarbledrandomtextofdigitsandletters',
    'transport_protocol': 'TCP'},
   {'port': 47808, 'service_name': 'BACNET', 'transport_protocol': 'UDP'}],
  'location': {'continent': 'North America',
   'country': 'United States',
   'country_code': 'US',
   'city': 'Denver',
   'postal_code': '80908',
   'timezone': 'America/Denver',
   'province': 'Colorado',
   'coordinates': {'latitude': 39.0234, 'longitude': -104.6926},
   'registered_country': 'United States',
   'registered_country_code': 'US'},
  'autonomous_system': {'asn': 7922,
   'description': 'CHARTER-7922',
   'bgp_prefix': '11.22.33.44/55',
   'name': 'CHARTER-7922',
   'country_code': 'US'},
  'operating_system': {'part': 'o', 'source': 'OSI_APPLICATION_LAYER'},
  'last_updated_at': '2022-08-23T12:51:39.427Z',
  'dns': {'reverse_dns': {'names': ['somebusiness.net']}}}]

如果我尝试使用 Pandas:

df = pd.DataFrame(data)

print(df.columns)

将返回:

Index(['ip', 'services', 'location', 'autonomous_system', 'operating_system',
       'last_updated_at', 'dns'],
      dtype='object')

Pandas for each ip 在查询中是否有可能返回所有坐标?在上面的示例中,它的 'coordinates': {'latitude': 39.0234, 'longitude': -104.6926}

我想我可以在没有 Pandas 的情况下使用类似的东西:

loc_data = []
for device in page:
    for info in device.keys():
        try:
            coords = device['location']['coordinates']
            loc_data.append(coords)
        except:
            continue

这将打印:

[{'latitude': 39.0234, 'longitude': -104.6926},
 {'latitude': 39.0234, 'longitude': -104.6926},
 {'latitude': 39.0234, 'longitude': -104.6926},
 {'latitude': 39.0234, 'longitude': -104.6926},
 {'latitude': 39.0234, 'longitude': -104.6926},
 {'latitude': 39.0234, 'longitude': -104.6926}]

但是我希望尽可能只使用 Pandas 吗?希望这是有道理的!

谢谢

最佳答案

试试这个:

df = pd.DataFrame(data)
data["coordinates"]=data["location"].apply(lambda x:x["coordinates"])

如果您的意思是仅使用 pandas 从一开始就使用 coordinates 列创建数据框这不是解决方案

关于python - api查询的pandas df,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/73490286/

相关文章:

python - 使用 dill 库时出现 TypeError : can't pickle _tkinter. tkapp 对象

python - 如何为其他列与 Pandas 交互的特定列设置默认值?

python - 将几乎没有或没有异常的名称聚类/分组到 Pandas 中的聚类中

python - 从 DataFrame 到嵌套的 Json 对象

Python行与列之间的交互

python - Django All-Auth django.contrib.auth.backends.ModelBackend 语法无效

python - 比较神经网络在两个特征子集上的结果

python - 为什么我不能只添加 Content-Type :text/html to a text file when Python can?

python - 如何从utcnow中提取日、月、年?

pandas - 是否可以将季度数据转换为月度数据?