在Python/Pandas中重新排列数据:将特定列vlaues转换为标题
我得到了一个大型数据集,其数据排列如下:在Python/Pandas中重新排列数据:将特定列vlaues转换为标题,python,pandas,Python,Pandas,我得到了一个大型数据集,其数据排列如下: location cost year 1 23.15 1986 1 23.91 1988 1 23.31 1989 1 23.91 1993 1 22.98 1994 1 23.99 1995 1 23.71 1997 1 23.01 1999 2 23.2
location cost year
1 23.15 1986
1 23.91 1988
1 23.31 1989
1 23.91 1993
1 22.98 1994
1 23.99 1995
1 23.71 1997
1 23.01 1999
2 23.21 2000
2 24.28 2004
2 24.4 2005
我想重新排列它,使它的形式如下:
location 1985 1986 1987 1988
1 20.00 20.00 20.0 20.0
2 20.00 20.00 20.0 20.0
3 20.00 20.00 20.0 20.0
4 20.00 20.00 20.0 20.0
5 20.00 20.00 20.0 20.0
(注意:忽略新成本都是20.0。我的目标是将年份
列中的值转换为标题,以便每个位置
只列出一次,特定年份的成本
位于该列中。)
有没有一种简单的方法可以做到这一点?我已经研究了groupy
和transpose
,但是没有能够产生任何接近我想要的东西
提前感谢您提供的任何提示。您需要使用
pivot\u table
:
pd.pivot_table(df, index='location', columns='year', values='cost', fill_value=0)
您的样品:
#Out[11]:
#year 1986 1988 1989 1993 1994 1995 1997 1999 2000 \
#location
#1 23.15 23.91 23.31 23.91 22.98 23.99 23.71 23.01 0.00
#2 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00 23.21
#year 2004 2005
#location
#1 0.00 0.0
#2 24.28 24.4
为什么所有列都是
20.0[0]
?只是为了示例位置;这些值不是真的,有点混乱。可能值得显示您期望的实际值。查看当前代码也可能很好。