首页 > 解决方案 > 如何在 Pandas 中将 Nonetype 对象转换为字符串或 DataFrame

问题描述

我的程序中的“NoneType”对象存在一些问题(写在熊猫上)。这是我的代码:

import asyncio
from aiohttp import ClientSession
from pyairvisual import Client
import pandas as pd

place = ['Brussels','Steenokkerzeel','Antwerpen','Aarschot','Amsterdam','London']
state1 = ['Brussels Capital','Flanders','Flanders','Flanders','North Holland','England']

n = 2
async def main() -> None:
    """Create the aiohttp session and run the example."""
    async with ClientSession() as websession:
        client = Client('fWw2GEy25CqmFQMaA', websession)

        data = await client.data.city(
        city = place[n], state = state1[n], country = 'Belgium')
        print(data)
asyncio.get_event_loop().run_until_complete(main())

我试过这个:

asyncio.get_event_loop().run_until_complete(main()).to_string()

但结果是:

{'city': 'Antwerpen', 'state': 'Flanders', 'country': 'Belgium', 'location': 
{'type': 'Point', 'coordinates': [4.34100506499574, 51.1702980406645]}, 
'current': {'weather': {'ts': '2018-10-30T06:00:00.000Z', 'hu': 60, 'ic': 
'09n', 'pr': 986, 'tp': 4, 'wd': 350, 'ws': 1.5}, 'pollution': {'ts': '2018- 
 10-30T07:00:00.000Z', 'aqius': 33, 'mainus': 'p2', 'aqicn': 16, 'maincn': 
 'n2'}}}
 ---------------------------------------------------------------------------
 AttributeError                            Traceback (most recent call last)
 <ipython-input-22-a1764c0a80fe> in <module>()
 ----> 1 asyncio.get_event_loop().run_until_complete(main()).to_string()

 AttributeError: 'NoneType' object has no attribute 'to_string'

我想获取荣誉之间的数据并将其设置为字符串或 DataFrame,但我不知道如何将“NoneType”对象转换为字符串或 DataFrame。其他人知道解决方案吗?

谢谢你。

标签: pythonpandas

解决方案


正如您通过类型提示所指示的那样,您当前正在None从 coroutine返回。main()(并且因为的返回值print()None)。

loop.run_until_complete()将传输 的返回值main(),即None,并且您正尝试调用None.to_string()作为结果。

您需要returnmain(). 那是什么取决于你:

async def main() -> None:
    async with ClientSession() as websession:
        client = Client('fWw2GEy25CqmFQMaA', websession)
        data = await client.data.city(
            city=place[n], state=state1[n], country='Belgium')
    return data

如果您想要一个字符串,而不是.to_string(),请在 asyncio 调用的结果上使用json.dumps()。如果您需要 DataFrame,请查看 Pandas 文档,了解如何从 Python 字典中实例化 DataFrame。


推荐阅读