简体   繁体   English

将M x(n * N)转换为(n * M)x N数据帧

[英]Turn M x (n*N) into (n*M) x N dataframe

I have a dataframe df1 with M rows and n*N columns. 我有一个具有M行和n*N列的数据df1 The columns are named 列名为

1.1,...,1.N,2.1,...,2.N,...n.1,...nN

The rows are indexed 1,...M . 这些行的索引为1,...M

What is an elegant way to turn this into a new dataframe df2 with n*M rows indexed 1.1,...,1.M,...,n.1,...nM and N columns named 1,...,N , such that 有什么df2方法将其转换为新的数据帧df2其中n * M行的索引为1.1,...,1.M,...,n.1,...nMN列名为1,...,N ,这样

df2.iloc[i*M+j,:]==df1.iloc[j,i*n:(i+1)*N]

Use Series.str.split with DataFrame.stack and last flatten MultiIndex by f-string s: 使用Series.str.splitDataFrame.stack和最后一个压平MultiIndexf-string S:

df.columns = df.columns.str.split('.', expand=True)
df = df.stack(0)
df.index = [f'{a}.{b}' for a, b in df.index]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM