将特定的选定列提取到新DataFrame中作为副本 [英] Extracting specific selected columns to new DataFrame as a copy

查看:364
本文介绍了将特定的选定列提取到新DataFrame中作为副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有4列的pandas DataFrame,我想创建一个 new Dataframe,它仅 具有三列.这个问题类似于:从数据框中提取特定列,但是下面的代码不起作用,会引发错误,并且肯定不是熊猫的方式.

I have a pandas DataFrame with 4 columns and I want to create a new DataFrame that only has three of the columns. This question is similar to: Extracting specific columns from a data frame but for pandas not R. The following code does not work, raises an error, and is certainly not the pandasnic way to do it.

import pandas as pd
old = pd.DataFrame({'A' : [4,5], 'B' : [10,20], 'C' : [100,50], 'D' : [-30,-50]})
new = pd.DataFrame(zip(old.A, old.C, old.D)) # raises TypeError: data argument can't be an iterator 

什么是熊猫人做的方式?

What is the pandasnic way to do it?

推荐答案

有一种方法可以做到,它实际上看起来类似于R

There is a way of doing this and it actually looks similar to R

new = old[['A', 'C', 'D']].copy()

在这里,您只是从原始数据框中选择所需的列,并为这些列创建变量.如果您想完全修改新的数据框,则可能需要使用.copy()来避免SettingWithCopyWarning.

Here you are just selecting the columns you want from the original data frame and creating a variable for those. If you want to modify the new dataframe at all you'll probably want to use .copy() to avoid a SettingWithCopyWarning.

另一种方法是使用filter,它将默认创建一个副本:

An alternative method is to use filter which will create a copy by default:

new = old.filter(['A','B','D'], axis=1)

最后,根据原始数据框中的列数,使用drop表示这一点可能更为简洁(默认情况下也会创建一个副本):

Finally, depending on the number of columns in your original dataframe, it might be more succinct to express this using a drop (this will also create a copy by default):

new = old.drop('B', axis=1)

这篇关于将特定的选定列提取到新DataFrame中作为副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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