Skip to main content
 首页 » 编程设计

Python Multi index function with order preserving or other possible solution in split columns

2025年01月19日14artech

我有以下格式的数据集:

county   area    pop_2006    pop_2007    life_2006    life_2007 
01001    275      1037         1052         102          121 
01003    394      2399         2424         438          221 
01005    312      1638         1647         660          221 

我需要这样的格式:

county    year   area      pop    life 
01001     2006   275      1037     102 
01001     2007   275      1052     121 
01003     2006   394      2399     438 
01003     2007   394      2424     221 
01005     2006   312      1638     660 
01005     2007   312      1647     221 

我试过 MultiIndex,但它会生成按字典顺序排列的列。 (显然,我对 Python/Pandas 几乎一窍不通,所以请多多关照。)

请您参考如下方法:

你可以使用 wide_to_long , 它与在 R 中使用 tidyr 非常相似。

import pandas as pd 
dat = pd.DataFrame(data={"county": ["01001", "01003", "01005"],  
                         "area": [275, 394, 312], 
                         "pop_2006": [1037, 2399, 1638], 
                         "pop_2007": [1052, 2424, 1647], 
                         "life_2006": [102, 438, 660], 
                         "life_2007": [121, 221, 221]}) 
pd.wide_to_long(dat,['life','pop'],i=['county','area'],j='yea‌​r',sep='_').reset_index(drop=False) 
 
 
Out[27]:  
  county  area yea‌​r  life   pop 
0  01001   275   2006   102  1037 
1  01001   275   2007   121  1052 
2  01003   394   2006   438  2399 
3  01003   394   2007   221  2424 
4  01005   312   2006   660  1638 
5  01005   312   2007   221  1647