【问题标题】:stack columns in dataframe, and also stack index column堆栈数据框中的列,以及堆栈索引列
【发布时间】:2013-06-10 04:39:27
【问题描述】:

我在从 pandas 的数据框中堆叠列时遇到问题,此外还堆叠一列并使其成为不包含唯一值的索引列。

>>> ds
  respondent  brand engine  country  aware  aware_2  aware_3  age  volvo  resp
0          a  volvo      p      swe      1        0        1   23   True     1
1          b  volvo   None      swe      0        0        1   45   True     2
2          c    bmw      p       us      0        0        1   56  False     3
3          d    bmw      p       us      0        1        1   43  False     2
4          e    bmw      d  germany      1        0        1   34  False     1
5          f   audi      d  germany      1        0        1   59  False     2
6          g  volvo      d      swe      1        0        0   65   True     3
7          h   audi      d      swe      1        0        0   78  False     2
8          i  volvo      d       us      1        1        1   32   True     2

我想创建一个新的数据框,其中包含 awareaware_2aware_3 列以及 resp 列堆叠。

【问题讨论】:

  • 你能澄清一下你真正想要什么吗?怎么叠? (你能给出前几行吗?)
  • 我想堆叠虚拟变量(aware、aware_2、aware_3),并分别堆叠 resp 变量并将堆叠的虚拟变量与该变量相关联。所以它应该是一个有 2 个堆叠列的新数据集

标签: python indexing stack pandas


【解决方案1】:

这就是你所追求的吗?

In [11]: df1 = df.set_index(['aware', 'aware_2', 'aware_3', 'resp'])

In [12]: df1.columns.name = 'heading'

In [13]: df1.stack()
Out[13]:
aware  aware_2  aware_3  resp  heading
1      0        1        1     respondent          a
                               brand           volvo
                               engine              p
                               country           swe
                               age                23
                               volvo            True
0      0        1        2     respondent          b
                               brand           volvo
                               engine           None
                               country           swe
                               age                45
                               volvo            True
...

【讨论】:

  • 实际上不,我想在数据框中有 2 列,一列是堆叠的假人,另一列 (resp) 堆叠在它旁边
猜你喜欢
  • 2018-09-16
  • 1970-01-01
  • 2018-01-26
  • 2015-08-22
  • 2021-08-07
  • 1970-01-01
  • 2014-03-29
  • 2013-07-02
  • 1970-01-01
相关资源
最近更新 更多