如何将两个Pandas Dataframe列彼此堆叠? [英] How do you stack two Pandas Dataframe columns on top of each other?

查看:405
本文介绍了如何将两个Pandas Dataframe列彼此堆叠?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有库函数或正确的方法将两个Pandas数据框列彼此堆叠?

Is there a library function or correct way of stacking two Pandas data frame columns on top of each other?

例如将4列分成2列:

a1  b1  a2  b2
 1   2   3   4
 5   6   7   8

c   d
1   2
5   6
3   4
7   8

我阅读的有关Pandas Data Frames的文档大部分只涉及串联行和进行行操作,但是我敢肯定必须有一种方法来完成我所描述的事情,并且我相信它非常简单.

The documentation for Pandas Data Frames that I read for the most part only deal with concatenating rows and doing row manipulation, but I'm sure there has to be a way to do what I described and I am sure it's very simple.

任何帮助都会很棒.

推荐答案

您可以使用pandas.DataFrame.iloc选择前两列和后两列.然后,将两个部分的列名称更改为cd.然后,您可以使用pandas.concat加入他们.

You can select the first two and second two columns using pandas.DataFrame.iloc. Then, change the column name of both parts to c and d. Afterwards, you can just join them using pandas.concat.

import pandas as pd
import numpy as np

df = pd.DataFrame(np.arange(1, 9).reshape((2, 4)),
        columns=["a1", "b1", "a2", "b2"])

part1 = df.iloc[:,0:2]
part2 = df.iloc[:,2:4]

new_columns = ["c", "d"]
part1.columns = new_columns
part2.columns = new_columns

print pd.concat([part1, part2], ignore_index=True)

这给您:

   c  d
0  1  2
1  5  6
2  3  4
3  7  8

这篇关于如何将两个Pandas Dataframe列彼此堆叠?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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