简体   繁体   English

熊猫转置concat()

[英]Pandas transpose concat()

How to transpose a DataFrame returned by concat() ? 如何转置concat()返回的DataFrame

df = DataFrame([
            dict(a=1, b=10, c=41),
            dict(a=1, b=20, c=42),
            ])

concat([df, df]).T

I get : 我得到:

AttributeError: 'DataFrame' object has no attribute 'dtypes' !

If I try : 如果我尝试:

concat([df, df]).T.to_dict()

I get : 我得到:

RuntimeError: maximum recursion depth exceeded in cmp

I think this is related to the duplicates introduced by concat() in the index but didn't find a workaround. 我认为这与concat()在索引中引入的重复项有关,但未找到解决方法。

You can specify hierarchical index using keys : 您可以使用keys指定层次结构索引:

In [288]: concatenated = concat([df,df], keys=['first', 'second'])

In [289]: print concatenated.T
   first      second    
       0   1       0   1
a      1   1       1   1
b     10  20      10  20
c     41  42      41  42

In [290]: print concatenated.T.to_dict().values()
[{'a': 1, 'c': 41, 'b': 10}, {'a': 1, 'c': 41, 'b': 10}, {'a': 1, 'c': 42, 'b': 20}, {'a': 1, 'c': 42, 'b': 20}]

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

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