繁体   English   中英

按组将列转换为行

[英]Convert columns to rows by groups

我有一个这样的数据框

Chennai
6200SqFT
10,000 Population
Mumbai
5000sqFT
17,000 Population

我想这样转换

Chennai    6200SqFT    10,000 Population
Mumbai     5000SqFT    17,000 Population

IIUC,您可以采用以下方法:

假设您的数据框如下所示:

print(df)
                   0
0            Chennai
1           6200SqFT
2  10,000 Population
3             Mumbai
4           5000sqFT
5  17,000 Population

np.reshape解决

output  = pd.DataFrame(df[0].to_numpy().reshape(-1,3))
#or output  = pd.DataFrame(df[0].values.reshape(-1,3))

输出:

         0         1                  2
0  Chennai  6200SqFT  10,000 Population
1   Mumbai  5000sqFT  17,000 Population

如果您有不均匀的线条(不是 3 的倍数,请尝试):

output = pd.concat([g.reset_index(drop=True) 
         for _,g in df.groupby(df.index//3)],axis=1).T.reset_index(drop=True)

试试下面的代码,

df_new = pd.DataFrame(df.values.reshape(-1,3), columns=['town', 'area', 'population'])
df_new.show()

输出

    town     area           population
0   Chennai 6200SqFT    10,000 Population
1   Mumbai  5000sqFT    17,000 Population

试试这个,因为有人在之前的评论中提到使用切片

>>> a,b,c = df[::3].values.reshape(-1), df[1::3].values.reshape(-1), df[2::3].values.reshape(-1)

>>> pd.DataFrame({'a':a,'b':b,'c':c}, index=range(len(a)))
         a         b                  c
0  Chennai  6200SqFT  10,000 Population
1   Mumbai  5000sqFT  17,000 Population

output = pd.concat([g.reset_index(drop=True) for _,g in df.groupby(df.index//3)],axis=1).T.reset_index(drop=True)

由 anky_91 发表

暂无
暂无

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

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