【问题标题】:IP2Location record to Pandas DataFrameIP2Location 记录到 Pandas DataFrame
【发布时间】:2021-01-30 15:14:06
【问题描述】:

我已使用 IP2Location 收集有关 IP 地址的信息,并且我希望它在 DataFrame 中,但是当我尝试使用 pd.json_normalize(ip) 时出现错误。 AttributeError: 'IP2LocationRecord' object has no attribute 'values'

我从IP2Location得到的信息就是这种格式,

{'ip': '66.249.79.244', 'country_short': 'US', 'country_long': 'United States of America', 'region': 'California', 'city': 'Mountain View', 'latitude': 37.405991, 'longitude': -122.078514, 'zipcode': '94043', 'timezone': '-08:00'}

我也尝试过使用pd.DataFrame,但是df中的结果是空的,只看到了列名。

df = pd.DataFrame(ip, columns = ['ip','country_short','country_long','region','city','latitude','longitude','zipcode','timezone'])

预期结果

     ip               country_short    country_long        ....       zipcode      timezone
0    66.249.69.244    US               United States of America       94043        -08:00

【问题讨论】:

    标签: python pandas dataframe ip2location


    【解决方案1】:

    请注意错误:

    AttributeError: 'IP2LocationRecord' object ...

    您要做的是将IP2LocationRecord 类型的对象转换为pandas.DataFrame,这是不可能的(您必须直接解压缩所有值,或者从IP2LocationRecord 的字段中创建一个字典) . 你在这里看到的:

    {'ip': '66.249.79.244', 'country_short': 'US', 'country_long': 'United States of America', 'region': 'California', 'city': 'Mountain View', 'latitude': 37.405991, 'longitude': -122.078514, 'zipcode': '94043', 'timezone': '-08:00'}
    

    实际上是repr(ip)repr python3 reference(而不是字典)

    【讨论】:

      猜你喜欢
      • 2013-11-07
      • 1970-01-01
      • 2020-10-18
      • 2018-02-07
      • 2016-01-25
      • 2017-07-19
      • 1970-01-01
      • 2021-12-09
      • 2017-09-09
      相关资源
      最近更新 更多