Python 3.x 如何使用转置将数据帧转换为矩阵
我有以下Python 3.x 如何使用转置将数据帧转换为矩阵,python-3.x,pandas,numpy,dataframe,Python 3.x,Pandas,Numpy,Dataframe,我有以下df code y_m count 101 2017-11 86 101 2017-12 32 102 2017-11 11 102 2017-12 34 102 2018-01 46 103 2017-11 56 103 2017-12 89 现在我想将这个df转换成一个矩阵,将列y\m转换为行,使作为矩阵单元格值进行计数,如下所示: 0 1
df
code y_m count
101 2017-11 86
101 2017-12 32
102 2017-11 11
102 2017-12 34
102 2018-01 46
103 2017-11 56
103 2017-12 89
现在我想将这个df
转换成一个矩阵,将列y\m
转换为行,使作为矩阵单元格值进行计数,如下所示:
0 1 2 3 4
0 -1 0 2017-11 2017-12 2018-01
1 0 354 153 155 46
2 101 118 86 32 -1
3 102 91 11 34 46
4 103 145 -1 89 -1
具体而言,-1
表示虚拟值,该虚拟值指示特定代码的y\m
的值不存在或保持矩阵形状0
表示“所有”值,该值聚合了code
或y_m
或code
和y_m
,例如单元格(1,1)
对所有y_m
和的计数值求和(1,2)
对2017-11
的计数进行求和 您可以先使用:
然后是最终格式,但得到混合值,带字符串的数字:
#change order of index and columns values for reindex
idx = df1.index[-1:].tolist() + df1.index[:-1].tolist()
cols = df1.columns[-1:].tolist() + df1.columns[:-1].tolist()
df2 = (df1.reindex(index=idx, columns=cols)
.reset_index()
.rename(columns={'code':-1})
.rename_axis(None,1))
#add columns to first row
df3 = df2.columns.to_frame().T.append(df2).reset_index(drop=True)
#reset columns names to range
df3.columns = range(len(df3.columns))
print (df3)
0 1 2 3 4
0 -1 0 2017-11 2017-12 2018-01
1 0 354 153 155 46
2 101 118 86 32 -1
3 102 91 11 34 46
4 103 145 56 89 -1
#change order of index and columns values for reindex
idx = df1.index[-1:].tolist() + df1.index[:-1].tolist()
cols = df1.columns[-1:].tolist() + df1.columns[:-1].tolist()
df2 = (df1.reindex(index=idx, columns=cols)
.reset_index()
.rename(columns={'code':-1})
.rename_axis(None,1))
#add columns to first row
df3 = df2.columns.to_frame().T.append(df2).reset_index(drop=True)
#reset columns names to range
df3.columns = range(len(df3.columns))
print (df3)
0 1 2 3 4
0 -1 0 2017-11 2017-12 2018-01
1 0 354 153 155 46
2 101 118 86 32 -1
3 102 91 11 34 46
4 103 145 56 89 -1