关注微信公共号:小程在线
关注CSDN博客:程志伟的博客
完整脚本在微信公共号有链接
import pandas as pd
import sys
print('Python version ' + sys.version)
print('Pandas version: ' + pd.__version__)
Python version 3.7.6 (default, Jan 8 2020, 20:23:39) [MSC v.1916 64 bit (AMD64)]
Pandas version: 1.0.1
# 我们的小数据集
d = {'one':[1,1],'two':[2,2]}
i = ['a','b']
# 创建一个 dataframe
df = pd.DataFrame(data = d, index = i)
df
Out[19]:
one two
a 1 2
b 1 2
df.index
Out[20]: Index(['a', 'b'], dtype='object')
# 把列(column)放置到索引位置
stack = df.stack()
stack
Out[21]:
a one 1
two 2
b one 1
two 2
dtype: int64
# 现在索引包含了原来的列名字
stack.index
Out[22]:
MultiIndex([('a', 'one'),
('a', 'two'),
('b', 'one'),
('b', 'two')],
)
unstack = df.unstack()
unstack
Out[23]:
one a 1
b 1
two a 2
b 2
dtype: int64
unstack.index
Out[24]:
MultiIndex([('one', 'a'),
('one', 'b'),
('two', 'a'),
('two', 'b')],
)
#用 T (转置), 我们可以把列和索引交换位置。
transpose = df.T
transpose
Out[25]:
a b
one 1 1
two 2 2
transpose.index
Out[26]: Index(['one', 'two'], dtype='object')