Pandas:DataFrame 中的 DataFrame

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17954520/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 21:02:42  来源:igfitidea点击:

Pandas: DataFrame within DataFrame

pandas

提问by jorge.santos

I need to create a DataFramethat contains columns of DataFrames. The DataFramesthat go in the column have different sizes and I am getting a StopIterationexception. This doesn't happen, when the DataFramesare of the same size. I know a Panelis more suitable for this, but I need a DataFramein this case.

我需要创建一个DataFrame包含DataFrames. 在DataFrames那走在列有不同的大小,我得到一个StopIteration例外。当DataFrames大小相同时,这不会发生。我知道 aPanel更适合于此,但DataFrame在这种情况下我需要 a 。

a=pd.DataFrame({'cat1':['one','two','three'],'cat2':['four','five','six']})
b=pd.DataFrame({'cat1':['ten','eleven'],'cat2':['twelve','thirteen']})
pd.DataFrame({'col1':{'row1':a,'row2':b}})

If I remove the 'three' and 'six' items from 'cat1', 'cat2' respectively, then this works fine. Any idea how I can achieve this?

如果我分别从“cat1”、“cat2”中删除“三个”和“六个”项目,那么这可以正常工作。知道我如何实现这一目标吗?

采纳答案by Jeff

this is not a good idea, you lose all efficiency because things are treated as objectdtype and operations will be quite slow (as operations cannot be done via c-level base types, like float/int). Better is to use a multi-level index, which can easily encompass what I think you want

这不是一个好主意,您会失去所有效率,因为事情被视为objectdtype 并且操作将非常缓慢(因为操作不能通过 c 级基本类型完成,例如 float/int)。更好的是使用多级索引,它可以轻松包含我认为你想要的

In [20]: a
Out[20]: 
    cat1  cat2
0    one  four
1    two  five
2  three   six

In [21]: b
Out[21]: 
     cat1      cat2
0     ten    twelve
1  eleven  thirteen

In [22]: pd.concat([ a, b ], keys={ 'row1' : a, 'row2' : b })
Out[22]: 
          cat1      cat2
row1 0     one      four
     1     two      five
     2   three       six
row2 0     ten    twelve
     1  eleven  thirteen