首页 > 解决方案 > Python将“pandas.core.series.Series”列表从地图调用折叠成数据框

问题描述

我是 python 新手,希望有人能帮助我掌握map. 我有一个函数myfunc,它在数据框中获取一列,并为每一列创建一个计算,生成一个 JSON,然后我将其转换为数据框。下面是我正在做的伪代码。

例如

def myfunc (factor):
    
    # This is the API we are posting to
    str_url = "www.foourl.com"

    # This is the factor we post to try and get the result
    request_string = [{"foo":factor}]
          
    header = {"content-type": "application/json","AUTH-TOKEN": "Foo"}
    # We post it using our authorization and Token
    response = requests.post(str_url , data=json.dumps(request_string), headers=header)
    
    # convert response to json format and then to the dataframe
    results_json = response.json()
    return(pd.json_normalize(results_json))

然后我使用下面的代码执行我的函数,它完美地工作。我可以使用 result[1] 访问每个结果,以获取因子 [1] 的数据帧结果、因子 [2] 的结果 [2] 等等。它返回一个 <class 'pandas.core.series.Series'>

# Import in the excel sheet and get the factors
df = pd.read_excel ('ref_data/search_factors.xlsx')
test = df['factor_number']

# Run the API for every factor
# Collapse the list then into a dataframe
result = test.map(myfunc)

我的问题是

由于所有结果都是数据框并且结构完全相同(5列都具有相同的名称),有没有一种方法可以在地图的所有迭代之后将所有内容折叠成一个数据框

例如,我知道R你可以使用 bind_rowsdplyr或类似的东西map_df来做同样的事情。它们在python中是等价的吗?

标签: pythonpandasdataframe

解决方案


是的,pandas我们有concat

df=pd.concat(result.tolist())

推荐阅读