简体   繁体   English

pandas:将一系列 DataFrame 转换为单个 DataFrame

[英]pandas: Convert Series of DataFrames to single DataFrame

I have a pandas Series object with each value being a DataFrame .我有一个 pandas Series对象,每个值都是一个DataFrame I am trying convert this into a single DataFrame with all of the Series values (individual DataFrame ) stacked on top of each other.我正在尝试将其转换为单个DataFrame ,其中所有Series值(单个DataFrame )彼此堆叠。 How can I achieve this without a loop?我怎样才能在没有循环的情况下实现这一点?

A toy example below to generate the test object ( results ).下面的玩具示例用于生成测试对象( results )。

import pandas as pd
import numpy as np
numrows = 10000

def toy_function(x):
    silly_sequence = np.random.uniform(10, 100, (x+1))
    toy = pd.DataFrame({'ID':pd.Series(np.random.random_integers(1,20,3)),'VALUE':pd.Series((np.median(silly_sequence),np.mean(silly_sequence), np.max(silly_sequence)))})

    return toy

results = pd.DataFrame({'ID':range(numrows)})['ID'].apply(toy_function)

results is of Series type and each element is a DataFrame like so: resultsSeries类型,每个元素都是一个DataFrame ,如下所示:

In [1]: results[1]
Out[1]: 
   ID      VALUE
0  17  40.035398
1   8  40.035398
2  20  66.483083

I am looking for a way to stack results[1] , results[2] etc. on top of each other to yield a DataFrame like this:我正在寻找一种将results[1]results[2]等堆叠在一起以产生如下 DataFrame 的方法:

   ID      VALUE
0  17  40.035398
1   8  40.035398
2  20  66.483083
4  12  25.035398
5   1  25.135398
6  19  65.553083
...

Try using pd.concat .尝试使用pd.concat At the very least, pd.concat(series.tolist()) should work.至少, pd.concat(series.tolist())应该可以工作。

Its default is to take a list of pandas dataframes or series and return them tacked end on end.它的默认设置是获取 pandas 数据框或系列的列表,并将它们端接返回。 http://pandas.pydata.org/pandas-docs/stable/merging.html http://pandas.pydata.org/pandas-docs/stable/merging.html

连接结果并在这样做时忽略您的索引:

df_stacked = pd.concat([r for r in results], ignore_index=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM