pd.wide_to_long()

pd.wide_to_long()

pd.wide_to_long(df,stubnames(提取以指定字符串开头的列),i(用作索引的列),j(提取开头后剩余的部分会成一列,在此指定列名),sep(分隔符),suffix(捕获正则表达式匹配的后缀))

In [34]:
 
df = pd.DataFrame({"A1970" : {0 : "a", 1 : "b", 2 : "c"},
...                    "A1980" : {0 : "d", 1 : "e", 2 : "f"},
...                    "B1970" : {0 : 2.5, 1 : 1.2, 2 : .7},
...                    "B1980" : {0 : 3.2, 1 : 1.3, 2 : .1},
...                    "X"     : dict(zip(range(3), np.random.randn(3)))
...                   })
 
 
In [36]:
df["id"] = df.index
df
 
 
Out[36]:
 A1970A1980B1970B1980Xid
0 a d 2.5 3.2 -0.116507 0
1 b e 1.2 1.3 0.026888 1
2 c f 0.7 0.1 1.469079 2
In [39]:
 
pd.wide_to_long(df,['A','B'],i='id',j='year')
 
 
Out[39]:
  XAB
idyear   
01970 -0.116507 a 2.5
11970 0.026888 b 1.2
21970 1.469079 c 0.7
01980 -0.116507 d 3.2
11980 0.026888 e 1.3
21980 1.469079 f 0.1
In [9]:
 df = pd.DataFrame({
...     'famid': [1, 1, 1, 2, 2, 2, 3, 3, 3],
...     'birth': [1, 2, 3, 1, 2, 3, 1, 2, 3],
...     'ht1': [2.8, 2.9, 2.2, 2, 1.8, 1.9, 2.2, 2.3, 2.1],
...     'ht2': [3.4, 3.8, 2.9, 3.2, 2.8, 2.4, 3.3, 3.4, 2.9]
... })
 
 
In [10]:
 
df
 
 
Out[10]:
 famidbirthht1ht2
0 1 1 2.8 3.4
1 1 2 2.9 3.8
2 1 3 2.2 2.9
3 2 1 2.0 3.2
4 2 2 1.8 2.8
5 2 3 1.9 2.4
6 3 1 2.2 3.3
7 3 2 2.3 3.4
8 3 3 2.1 2.9
In [11]:
l=pd.wide_to_long(df,['ht'],i=['famid','birth'],j='age')
l
 
 
Out[11]:
   ht
famidbirthage 
111 2.8
2 3.4
21 2.9
2 3.8
31 2.2
2 2.9
211 2.0
2 3.2
21 1.8
2 2.8
31 1.9
2 2.4
311 2.2
2 3.3
21 2.3
2 3.4
31 2.1
2 2.9
In [45]:
w=l.unstack()
w
 
 
Out[45]:
  ht
 age12
famidbirth  
11 2.8 3.4
2 2.9 3.8
3 2.2 2.9
21 2.0 3.2
2 1.8 2.8
3 1.9 2.4
31 2.2 3.3
2 2.3 3.4
3 2.1 2.9
In [46]:
w.columns
 
 
Out[46]:
MultiIndex(levels=[['ht'], [1, 2]],
           labels=[[0, 0], [0, 1]],
           names=[None, 'age'])
In [47]:
 
w.columns=w.columns.map('{0[0]}{0[1]}'.format)
w.columns
 
 
Out[47]:
Index(['ht1', 'ht2'], dtype='object')
In [23]:
w.reset_index()
 
 
Out[23]:
 famidbirthht1ht2
0 1 1 2.8 3.4
1 1 2 2.9 3.8
2 1 3 2.2 2.9
3 2 1 2.0 3.2
4 2 2 1.8 2.8
5 2 3 1.9 2.4
6 3 1 2.2 3.3
7 3 2 2.3 3.4
8 3 3 2.1 2.9

posted on 2019-08-02 08:29  离云1  阅读(993)  评论(0)    收藏  举报

导航