在 python 中取消堆叠 csv 文件

Unstacking a csv file in python

我正在尝试取消堆叠 python 中的列,但它并没有完全按照我的预期进行。我的 table 看起来与此类似:

 Station_id   year   month   Day1   Day2 
 210018       1916     1      4        7
                       2      6      NaN
                       3      2       1
 256700       1917     1      NaN     8
                       2       6      9
                       3       2      0

我想按月拆分,这样一个月中的所有日子都排成一行。然后,第一个月的两天将首先开始,然后是第二个月的两天,然后是第三个月的两天,依此类推。在此之后我不再需要月份列,我尝试删除它并取消堆叠,但它不起作用。

table 看起来像这样:

 Station_id   year 
 210018       1916         4   7  6  NaN  2  1
 256700       1917        NaN  8  6   9   2  0   

当我现在尝试 df.unstack(2) 时,它 returns 结果如下所示:

Station_id   year 
 210018       1916         4   6  2  7  NaN   1
 256700       1917        NaN  6  2  8   9    0

如有任何帮助,我们将不胜感激

pandas所做的没有任何问题。您只需要交换一些列级别,然后对它们进行排序。

获取您的数据并制作一个可重现的示例 (python 3) 您会得到:

from io import StringIO
import pandas

datafile = StringIO("""\
Station_id  year  month  Day1  Day2
     210018  1916      1     4     7
     210018  1916      2     6   NaN
     210018  1916      3     2     1
     256700  1917      1   NaN     8
     256700  1917      2     6     9
     256700  1917      3     2     0
""")

df = pandas.read_table(datafile, sep='\s+', engine='python', 
                       index_col=['Station_id', 'year', 'month'])
print(df.unstack(level='month'))

               Day1       Day2       
month              1  2  3    1   2  3
Station_id year                       
210018     1916    4  6  2    7 NaN  1
256700     1917  NaN  6  2    8   9  0

在您看来,您认为将月份放在首位是合乎逻辑的,但您 pandas 无法知道这是否合理。所以你必须自己做:

df = pandas.read_table(datafile, sep='\s+', engine='python', 
                       index_col=['Station_id', 'year', 'month'])
xtab = df.unstack(level='month')
xtab.columns = xtab.columns.swaplevel(0, 1)
xtab = xtab.sort(axis=1)
print(xtab)


month              1         2         3     
                Day1 Day2 Day1 Day2 Day1 Day2
Station_id year                              
210018     1916    4    7    6  NaN    2    1
256700     1917  NaN    8    6    9    2    0