如何在python中将特定范围的列展平为一列?
我有一个维度为214行972列的数据表 我想每108列取一列,然后平铺成一列 那么输出表的维度将是23112(=214*108)行和9列。 我尝试了如何在python中将特定范围的列展平为一列?,python,pandas,datatable,flatten,Python,Pandas,Datatable,Flatten,我有一个维度为214行972列的数据表 我想每108列取一列,然后平铺成一列 那么输出表的维度将是23112(=214*108)行和9列。 我尝试了pd.concat和pd.flatte等等,但我只能将表中的所有列展平为一列 简单地说,下面是玩具桌。每两列拾取一列,并将其展平为一列。所以我想重塑;[5*6]至[10*3] a b c d e f g h i j k l m n o p q r s t u v w x y z 1 2 3 4
pd.concat
和pd.flatte
等等,但我只能将表中的所有列展平为一列
简单地说,下面是玩具桌。每两列拾取一列,并将其展平为一列。所以我想重塑;[5*6]至[10*3]
a b c d e f
g h i j k l
m n o p q r
s t u v w x
y z 1 2 3 4
这将转换为
a c e
g i k
m o q
s u w
y 1 3
b d f
h j l
n p r
t v x
z 2 4
我对python真的很陌生,太难理解了,,
谢谢你的帮助 IIUC:
print (pd.concat([pd.DataFrame(df.iloc[:,::2].values),
pd.DataFrame(df.iloc[:,1::2].values)])
.reset_index(drop=True))
或用数字n的列表进行概括:
n=2
print (pd.concat([pd.DataFrame(df.iloc[:,i::n].values) for i in range(n)])
.reset_index(drop=True))
0 1 2
0 a c e
1 g i k
2 m o q
3 s u w
4 y 1 3
5 b d f
6 h j l
7 n p r
8 t v x
9 z 2 4
您还可以使用:
甚至不使用类似Fortran的索引顺序进行重塑
使用列表理解,可以在一行中完成:
cols_to_flatten = 2 #change this as per your requirement
pd.concat([pd.concat([df[col] for col in df.columns[i:i+cols_to_flatten]], ignore_index=True) for i in range(0, df.shape[1], cols_to_flatten)], axis=1)
在阅读其他人对你问题的回答之前,我会这样做:
将熊猫作为pd导入
def concat_every(帧,每个):
frame=frame.copy()
新建_df=pd.DataFrame(
columns=范围(len(frame.columns)//每个)
)
对于新_df.列中的c:
col=frame.columns
new_df[c]=pd.concat(
[frame.pop(col[i])表示范围内的i(every)],
忽略索引=真
)
返回新的_df
df=pd.DataFrame({
0:[a'、'g'、'm'、's'、'y'],
1:[b'、'h'、'n'、't'、'z'],
2:[c','i','o','u',1],
3:[d','j','p','v',2],
4:[e','k','q','w',3],
5:[f','l','r','x',4],
})
df1=每(df,2)个混凝土
打印(df)
打印(df1)
pd.DataFrame(np.reshape(df.to_numpy(),(df.shape[0]*n,df.shape[1]//n),order='F'))
0 1 2
0 a c e
1 g i k
2 m o q
3 s u w
4 y 1 3
5 b d f
6 h j l
7 n p r
8 t v x
9 z 2 4
cols_to_flatten = 2 #change this as per your requirement
pd.concat([pd.concat([df[col] for col in df.columns[i:i+cols_to_flatten]], ignore_index=True) for i in range(0, df.shape[1], cols_to_flatten)], axis=1)