我有一个像这样的数据框
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)
关于python - 按组将列转换为行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59890272/