在同一df Python/Pandas中合并列 [英] Combining columns within the same df Python/Pandas

查看:366
本文介绍了在同一df Python/Pandas中合并列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编程世界的新手,无法弄清楚如何在pandas中连接列.我不想加入这些专栏,而是将它们彼此堆叠.

I'm new to the programming world and can't figure out how to concatenate columns in pandas. I'm not looking to join these columns, but rather stack them on top of each other.

这是我到目前为止的代码:

This is the code I have so far:

import pandas as pd
import numpy as np 

df = pd.read_excel("C:\\Users\\Kit Wesselhoeft\\Documents\\NEM\\Northend Manufacturing_deletecol.xlsx")

print(df)

df = pd.concat(['A','A'])

print(df)

此处的图片

我想合并所有列,以使所有A彼此重叠,与B相同-E.

I want to combine all the columns so that all the A's sit on top of each other, Same with the B's - E's.

我该怎么做?我想念什么吗?

How can I do this? Am I missing something?

推荐答案

当您确切知道列的位置时,以下示例是相关的.建立在 ALollz的代码上:

The following example is relevant when you exactly know where your columns are. Building on ALollz's code:

import numpy as np
import pandas as pd

np.random.seed(123)
df = pd.DataFrame(np.random.randint(1, 10, (3, 15)),
                  columns=list('BACDE')*3)
#   B  A  C  D  E  B  A  C  D  E  B  A  C  D  E
#0  3  3  7  2  4  7  2  1  2  1  1  4  5  1  1
#1  5  2  8  4  3  5  8  3  5  9  1  8  4  5  7
#2  2  6  7  3  2  9  4  6  1  3  7  3  5  5  7

# Using iloc

df1 = df.iloc[:, :5]

df2 = df.iloc[:,5:10]

df3 = df.iloc[:,10:]

df_final= pd.concat([df1,df2,df3]).reset_index(drop=True)

结果df_final:

    B   A   C   D   E

0   3   3   7   2   4
1   5   2   8   4   3
2   2   6   7   3   2
3   7   2   1   2   1
4   5   8   3   5   9
5   9   4   6   1   3
6   1   4   5   1   1
7   1   8   4   5   7
8   7   3   5   5   7

这篇关于在同一df Python/Pandas中合并列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆