如何将多个列从Pandas数据框弹出到新数据框? [英] How do you pop multiple columns off a Pandas dataframe, into a new dataframe?

查看:220
本文介绍了如何将多个列从Pandas数据框弹出到新数据框?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下内容:

df = pd.DataFrame({'a':range(2), 'b':range(2), 'c':range(2), 'd':range(2)})

我想从数据框中弹出"两列("c"和"d")到一个新的数据框中,在原始df中保留"a"和"b".以下内容不起作用:

I'd like to "pop" two columns ('c' and 'd') off the dataframe, into a new dataframe, leaving 'a' and 'b' behind in the original df. The following does not work:

df2 = df.pop(['c', 'd'])

这是我的错误:

TypeError: '['c', 'd']' is an invalid key

除了执行以下操作之外,还有谁知道快速,一流的解决方案?

Does anyone know a quick, classy solution, besides doing the following?

df2 = df[['c', 'd']]
df3 = df[['a', 'b']]

我知道上面的代码键入起来不是 ,但是这就是为什么发明了DataFrame.pop的原因-为我们节省了从数据库中弹出一列的步骤.

I know the above code is not that tedious to type, but this is why DataFrame.pop was invented--to save us a step when popping one column off a database.

推荐答案

这将是一个两步过程(您 不能解决这个问题,因为正如正确提到的那样,pop适用于单列并返回系列).

This will have to be a two step process (you cannot get around this, because as rightly mentioned, pop works for a single column and returns a Series).

首先,切片df(步骤1),然后删除这些列(步骤2).

First, slice df (step 1), and then drop those columns (step 2).

df2 = df[['c', 'd']].copy()
del df[['c', 'd']] # df.drop(['c', 'd'], axis=1, inplace=True)

这是使用pd.concat的丑陋选择:

df2 = pd.concat([df.pop(x) for x in ['c', 'd']], 1)

这仍然是一个两步过程,但是您需要一行完成.

This is still a two step process, but you're doing it in one line.

df

   a  b
0  0  0
1  1  1

df2

   c  d
0  0  0
1  1  1

这篇关于如何将多个列从Pandas数据框弹出到新数据框?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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