如何使用 Pandas 将二维 table (DataFrame) 反转为一维列表?
How to reverse a 2-dimensional table (DataFrame) into a 1 dimensional list using Pandas?
我正在 Python/Pandas 寻找将二维 table 反转为一维列表的技巧。
我通常利用 Excel 函数来完成它,但我相信有一种聪明的 Python 方法可以做到。
步骤
Excel 方式的更多详情:
http://www.extendoffice.com/documents/excel/2461-excel-reverse-pivot-table.html
这应该可以解决问题:
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:]:
new_line = [line[0], name, cell]
new_table.append(new_line)
输出为:
[
['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]
]
例子取自http://pandas.pydata.org/pandas-docs/stable/reshaping.html
tl;dr,使用:
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')
我们将取消这个 table:
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
瞧!现在我们得到了想要的 table.
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
这种类型的操作也可以使用 pd.melt
来完成,它会反转 DataFrame。
如果 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
然后我们 select 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
相互堆叠:如果列值需要按特定顺序排列,则需要在熔化后对列进行排序。
我正在 Python/Pandas 寻找将二维 table 反转为一维列表的技巧。
我通常利用 Excel 函数来完成它,但我相信有一种聪明的 Python 方法可以做到。
步骤
Excel 方式的更多详情: http://www.extendoffice.com/documents/excel/2461-excel-reverse-pivot-table.html
这应该可以解决问题:
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:]:
new_line = [line[0], name, cell]
new_table.append(new_line)
输出为:
[
['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]
]
例子取自http://pandas.pydata.org/pandas-docs/stable/reshaping.html
tl;dr,使用:
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')
我们将取消这个 table:
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
瞧!现在我们得到了想要的 table.
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
这种类型的操作也可以使用 pd.melt
来完成,它会反转 DataFrame。
如果 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
然后我们 select 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
相互堆叠:如果列值需要按特定顺序排列,则需要在熔化后对列进行排序。