如何将二维表(DataFrame)反转为一维列表?

问题描述 投票:0回答:3

我正在 Python/Pandas 中寻找将二维表反转为一维列表的技巧。

我通常利用 Excel 函数来完成此操作,但我相信有一种聪明的 Python 方法可以做到这一点。

步骤

The steps of

Excel方式更多详情: http://www.extendoffice.com/documents/excel/2461-excel-reverse-pivot-table.html

python pandas dataframe pivot-table
3个回答
55
投票

这种类型的操作也可以使用

pd.melt
来完成,它会取消数据透视。

如果 DataFrame

df
看起来像这样:

  row labels  Tue  Wed  Thu  Sat  Sun  Fri  Mon
0      Apple   21   39   24   27   37   46   42
1     Banana   32   50   48   35   21   27   22
2       Pear   37   20   45   45   31   50   32

然后我们选择

row_labels
列作为我们的
id_var
并选择其余列作为我们的值 (
value_vars
)。我们甚至可以同时为列选择新名称:

>>> pd.melt(df, 
            id_vars='row labels', 
            value_vars=list(df.columns[1:]), # list of days of the week
            var_name='Column', 
            value_name='Sum of Value')

   row labels   Column   Sum of Value
0       Apple      Tue             21
1      Banana      Tue             32
2        Pear      Tue             37
3       Apple      Wed             39
4      Banana      Wed             50
5        Pear      Wed             20
...

value_vars
彼此堆叠:如果列值需要按特定顺序排列,则需要在熔化后对列进行排序。


3
投票

这应该可以解决问题:

table = [
            ["Lables", "A", "B", "C"],
            ["X", 1, 2, 3],
            ["Y", 4, 5, 6],
            ["Z", 7, 8, 9]
        ]

new_table = [["Row", "Column", "Data"]]
for line in table[1:]:
    for name, cell in zip(table[0], line)[1:]:       # py2
#   for name, cell in list(zip(table[0], line))[1:]: # py3
    
        new_line = [line[0], name, cell]
        new_table.append(new_line)
print(new_table)

输出为:

[
    ['Row', 'Column', 'Data'],
    ['X', 'A', 1],
    ['X', 'B', 2],
    ['X', 'C', 3],
    ['Y', 'A', 4],
    ['Y', 'B', 5],
    ['Y', 'C', 6],
    ['Z', 'A', 7],
    ['Z', 'B', 8],
    ['Z', 'C', 9]
]

1
投票

示例取自http://pandas.pydata.org/pandas-docs/stable/reshaping.html

tl;博士,使用:

from pandas import *
df.stack()

====================

让我们举一个例子来说明如何做到这一点。

先生成样本数据:

from pandas import *
import pandas.util.testing as tm; tm.N = 3
import numpy as np
def unpivot(frame):
    N, K = frame.shape
    data = {'value' : frame.values.ravel('F'),
            'variable' : np.asarray(frame.columns).repeat(N),
            'date' : np.tile(np.asarray(frame.index), K)}
    return DataFrame(data, columns=['date', 'variable', 'value'])
df = unpivot(tm.makeTimeDataFrame())
df2=  df.pivot('date', 'variable')

我们将取消透视此表:

               value                              
variable           A         B         C         D
date                                              
2000-01-03 -0.425081  0.163899 -0.216486 -0.266285
2000-01-04  0.078073  0.581277  0.103257 -0.338083
2000-01-05  0.721696 -1.311509 -0.379956  0.642527

运行:

df2=  df.pivot('date', 'variable')
print df2

瞧!现在我们得到了想要的表。

                        value
date       variable          
2000-01-03 A        -0.425081
           B         0.163899
           C        -0.216486
           D        -0.266285
2000-01-04 A         0.078073
           B         0.581277
           C         0.103257
           D        -0.338083
2000-01-05 A         0.721696
           B        -1.311509
           C        -0.379956
           D         0.642527
© www.soinside.com 2019 - 2024. All rights reserved.