Python 如何将一个数据帧转换为另一个数据帧?
主席Python 如何将一个数据帧转换为另一个数据帧?,python,dataframe,Python,Dataframe,主席 critic title rating 0 Jack Matthews Lady in the Water 3.0 1 Jack Matthews Snakes on a Plane 4.0 2 Jack Matthews You Me and Dupree 3.5 3 Jack Matthews Superman Returns 5.0 4 Jack Matthews The Night Listener 3.0
critic title rating
0 Jack Matthews Lady in the Water 3.0
1 Jack Matthews Snakes on a Plane 4.0
2 Jack Matthews You Me and Dupree 3.5
3 Jack Matthews Superman Returns 5.0
4 Jack Matthews The Night Listener 3.0
我想让它看起来像
critic Just My Luck Lady in the Water Snakes on a Plane Superman Returns The Night Listener You Me and Dupree
Claudia Puig 3.0 NaN 3.5 4.0 4.5 2.5
Gene Seymour 1.5 3.0 3.5 5.0 3.0 3.5
Jack Matthews NaN 3.0 4.0 5.0 3.0 3.5
Lisa Rose 3.0 2.5 3.5 3.5 3.0 2.5
Mick LaSalle 2.0 3.0 4.0 3.0 3.0 2.0
Toby NaN NaN 4.5 4.0 NaN 1.0
我试着使用
movie_rating= ratings.pivot(index='critic', columns='title',values='rating')
但它会创建额外的列名。像
title Just My Luck Lady in the Water Snakes on a Plane Superman Returns The Night Listener You Me and Dupree
critic
Claudia Puig 3.0 NaN 3.5 4.0 4.5 2.5
Gene Seymour 1.5 3.0 3.5 5.0 3.0 3.5
Jack Matthews NaN 3.0 4.0 5.0 3.0 3.5
Lisa Rose 3.0 2.5 3.5 3.5 3.0 2.5
Mick LaSalle 2.0 3.0 4.0 3.0 3.0 2.0
Toby NaN NaN 4.5 4.0 NaN 1.0
您看到的不是额外的列。这些是行和列的索引名称。行索引名为“批评家”,列索引名为“标题”。要使数据透视框显示时不显示它们,只需将索引和列的name参数设置为None即可 您可以看到title和critic分别是列和索引的名称属性
p.columns, p.index
# returns:
(Index(['hello', 'world'], dtype='object', name='title'),
Index(['A', 'B', 'C'], dtype='object', name='critic'))
要删除显示的名称,只需覆盖索引和列对象的name属性即可
p.columns, p.index
# returns:
(Index(['hello', 'world'], dtype='object', name='title'),
Index(['A', 'B', 'C'], dtype='object', name='critic'))
p.index.name = None
p.columns.name = None
p
# returns:
hello world
A 4 3
B 6 2
C 3 2