以CSV格式转换特定数据

时间:2015-05-30 16:08:39

标签: python csv pandas

我有一个csv文件,如下所示:

Month     Day   Year  Tmax
   4       1    1912    56
   4       2    1912    56
   4       3    1912    74
   4       4    1912    82
   4       5    1912    79
   4       1    1913    73
   4       2    1913    60
   4       3    1913    67
   4       4    1913    81
   4       5    1913    77

我希望它看起来像这样:

Year  Month   1     2     3      4     5 
 1912   4     56     56    74     82    79
 1913   4     73     60    67     81    77

因此,每个Day现在都是列标题,Tmax显示为列而不是行。我已经玩过拆散和转置,但似乎无法得到它。任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:3)

您可以将pd.pivot_table() index ['Year', 'Month'] columns 'Day' 'Tmax' In [10]: pd.pivot_table(df, values='Tmax', index=['Year', 'Month'], columns='Day') Out[10]: Day 1 2 3 4 5 Year Month 1912 4 56 56 74 82 79 1913 4 73 60 67 81 77 用于jsfiddle.net/gdc5ryqj/

body {
    margin-left: auto;
    margin-right: auto;
    width: 80%;
    background-color: #FFFFFF;
}
h1 {
    display:inline-block;
    background:#FF0000;
    border:2px solid black;
    clear:both;
}
.nav {
    display: block;
    position: absolute;
    top: -1px;
    float: left;
    overflow: auto;
}
.nav a {
    display:inline-block;
    width:88px;
    height:50px;
    font-family:"Comic Sans MS", Arial, Sans-serif;
    color:#FFFFFF;
    background-color:#008000;
    text-align:center;
    padding:0px;
    margin:0px;
    border-style:solid;
    border-color:#FFFFFF;
    border-width:1px;
    text-decoration:none;
}
.nav a:visited {
    color:#CCCCCC;
}
.nav a:hover, a:active {
    color:#008000;
    background-color:#CCCCCC;
}
.nav a#here {
    color:#008000;
    background-color:white;
}
ul.subnav {
    background-color:#009000;
    padding:0px;
    margin:0px;
    border:1px solid #009000;
    width:618px;
    height:18px;
    position:absolute;
    top:72px;
    left:220px;
}
ul.subnav li {
    display:block;
    width:123px;
    height:18px;
    background-color:#009000;
    list-style-type:none;
    margin:0px;
    padding:0px;
    border-width:0px;
    overflow:hidden;
    float:left;
}
ul.subnav a {
    display:block;
    width:123px;
    height:18px;
    font-family:"Comic Sans MS", Arial, Sans-serif;
    font-size:75%;
    font-weight:bold;
    color:#FFFFFF;
    background-color:#009000;
    text-align:center;
    padding:0px;
    border-width:0px;
    margin:0px;
    text-decoration:none;
}
ul.subnav a:visited {
    color:#CCCCCC;
}
ul.subnav a:hover, a:active {
    color:#008000;
    background-color:#CCCCCC;
}
ul.subnav a#here {
    color:#008000;
    background-color:white;
}
.note {
    background-color:#7A991A;
}
.text {
    background-color:white;
    font-family:"Comic Sans MS", Arial, Sans-serif;
    color:#008000;
    width:80%;
    left:10%;
}
.text a:link {
    color:#008000;
}
.text a:visited {
    color:#999999;
}