【问题标题】:Pandas transpose concat()熊猫转置 concat()
【发布时间】:2012-09-29 15:01:43
【问题描述】:

如何转置concat()返回的DataFrame

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

concat([df, df]).T

我明白了:

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

如果我尝试:

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

我明白了:

RuntimeError: maximum recursion depth exceeded in cmp

我认为这与索引中concat() 引入的重复项有关,但没有找到解决方法。

【问题讨论】:

  • 你能解释一下你想要达到的目标吗?
  • 我曾经用 df.T.to_dict().values() 对 DataFrame 值进行单元测试
  • 仅供参考,最新的熊猫版本能够支持索引重复,我相信在 0.8.0 之前不是这种情况。

标签: python pandas


【解决方案1】:

您可以使用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}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2022-07-09
    • 2015-12-24
    • 2021-12-12
    • 2019-07-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    相关资源
    最近更新 更多