本文翻译自:Selecting multiple columns in a pandas dataframe

I have data in different columns but I don't know how to extract it to save it in another variable. 我在不同的列中有数据,但是我不知道如何提取数据以将其保存在另一个变量中。

index  a   b   c
1      2   3   4
2      3   4   5

How do I select 'a' , 'b' and save it in to df1? 如何选择'a''b'并将其保存到df1?

I tried 我试过了

df1 = df['a':'b']
df1 = df.ix[:, 'a':'b']

None seem to work. 似乎没有任何工作。


#1楼

参考:https://stackoom.com/question/lLu1/在pandas数据框中选择多个列


#2楼

The column names (which are strings) cannot be sliced in the manner you tried. 列名(字符串)无法按照您尝试的方式进行切片。

Here you have a couple of options. 在这里,您有两个选择。 If you know from context which variables you want to slice out, you can just return a view of only those columns by passing a list into the __getitem__ syntax (the []'s). 如果您从上下文中知道要切出哪些变量,则可以通过将列表传递给__getitem__语法([])来仅返回那些列的视图。

df1 = df[['a','b']]

Alternatively, if it matters to index them numerically and not by their name (say your code should automatically do this without knowing the names of the first two columns) then you can do this instead: 另外,如果需要对它们进行数字索引而不是按其名称进行索引(例如,您的代码应在不知道前两列名称的情况下自动执行此操作),则可以执行以下操作:

df1 = df.iloc[:,0:2] # Remember that Python does not slice inclusive of the ending index.

Additionally, you should familiarize yourself with the idea of a view into a Pandas object vs. a copy of that object. 此外,您应该熟悉Pandas对象与该对象副本的视图概念。 The first of the above methods will return a new copy in memory of the desired sub-object (the desired slices). 上述方法中的第一个将在内存中返回所需子对象(所需切片)的新副本。

Sometimes, however, there are indexing conventions in Pandas that don't do this and instead give you a new variable that just refers to the same chunk of memory as the sub-object or slice in the original object. 但是,有时熊猫中有一些索引约定不这样做,而是为您提供了一个新变量,该变量仅引用与原始对象中的子对象或切片相同的内存块。 This will happen with the second way of indexing, so you can modify it with the copy() function to get a regular copy. 第二种索引方式将发生这种情况,因此您可以使用copy()函数对其进行修改以获取常规副本。 When this happens, changing what you think is the sliced object can sometimes alter the original object. 发生这种情况时,更改您认为是切片对象的内容有时会更改原始对象。 Always good to be on the look out for this. 始终对此保持警惕。

df1 = df.iloc[0,0:2].copy() # To avoid the case where changing df1 also changes df

To use iloc , you need to know the column positions (or indices). 要使用iloc ,您需要知道列位置(或索引)。 As the column positions may change, instead of hard-coding indices, you can use iloc along with get_loc function of columns method of dataframe object to obtain column indices. 由于列位置可能会发生变化,因此可以使用ilocget_loc对象的columns方法的get_loc函数一起使用,而不用对索引进行硬编码,以获取列索引。

{df.columns.get_loc(c):c for idx, c in enumerate(df.columns)}

Now you can use this dictionary to access columns through names and using iloc . 现在,您可以使用此词典通过名称和iloc访问列。


#3楼

In [39]: df
Out[39]: index  a  b  c
0      1  2  3  4
1      2  3  4  5In [40]: df1 = df[['b', 'c']]In [41]: df1
Out[41]: b  c
0  3  4
1  4  5

#4楼

Assuming your column names ( df.columns ) are ['index','a','b','c'] , then the data you want is in the 3rd & 4th columns. 假设您的列名( df.columns )为['index','a','b','c'] ,则所需的数据位于第3列和第4列中。 If you don't know their names when your script runs, you can do this 如果在脚本运行时不知道它们的名称,则可以执行此操作

newdf = df[df.columns[2:4]] # Remember, Python is 0-offset! The "3rd" entry is at slot 2.

As EMS points out in his answer , df.ix slices columns a bit more concisely, but the .columns slicing interface might be more natural because it uses the vanilla 1-D python list indexing/slicing syntax. 正如EMS在他的回答中指出的那样, df.ix列进行切片更为简洁,但是.columns切片界面可能更自然,因为它使用了香草1-D python列表索引/切片语法。

WARN: 'index' is a bad name for a DataFrame column. 警告: 'index'DataFrame列的错误名称。 That same label is also used for the real df.index attribute, a Index array. 该标签也用于实际的df.index属性,即Index数组。 So your column is returned by df['index'] and the real DataFrame index is returned by df.index . 因此,您的列由df['index']返回,而真正的DataFrame索引由df.index返回。 An Index is a special kind of Series optimized for lookup of it's elements' values. Index是一种特殊的Series针对其元素的值进行了优化。 For df.index it's for looking up rows by their label. 对于df.index,它用于按标签查找行。 That df.columns attribute is also a pd.Index array, for looking up columns by their labels. df.columns属性也是pd.Index数组,用于按标签查找列。


#5楼

You could provide a list of columns to be dropped and return back the DataFrame with only the columns needed using the drop() function on a Pandas DataFrame. 您可以提供要删除的列的列表,并使用Pandas DataFrame上的drop()函数仅返回需要的列。

Just saying 只是说

colsToDrop = ['a']
df.drop(colsToDrop, axis=1)

would return a DataFrame with just the columns b and c . 将返回仅包含列bc的DataFrame。

The drop method is documented here . drop方法记录在这里 。


#6楼

I realize this question is quite old, but in the latest version of pandas there is an easy way to do exactly this. 我知道这个问题已经很老了,但是在最新版本的熊猫中,有一种简单的方法可以做到这一点。 Column names (which are strings) can be sliced in whatever manner you like. 列名(即字符串) 可以按您喜欢的任何方式进行切片。

columns = ['b', 'c']
df1 = pd.DataFrame(df, columns=columns)

在pandas数据框中选择多个列相关推荐

  1. Python中dataframe数据框中选择某一列非空的行

    利用pandas自带的函数notnull可以很容易判断某一列是否为null类型,但是如果这一列中某一格为空字符串"",此时notnull函数会返回True,而一般我们选择非空行并不 ...

  2. Python:在Pandas数据框中查找缺失值

    How to find Missing values in a data frame using Python/Pandas 如何使用Python / Pandas查找数据框中的缺失值 介绍: (In ...

  3. python保存数据框_python – 如何将numpy数组作为对象存储在pandas数据框中?

    我有一系列图像,存储在CVS文件中,每个图像一个字符串,该字符串是9216空格分隔整数的列表.我有一个函数将其转换为96×96 numpy数组. 我希望将这个numpy数组存储在我的数据帧的一列而不是 ...

  4. python如何存储numpy数组_python – 如何将numpy数组作为对象存储在pandas数据框中?...

    我有一系列图像,存储在CVS文件中,每个图像一个字符串,该字符串是9216空格分隔整数的列表.我有一个函数将其转换为96×96 numpy数组. 我希望将这个numpy数组存储在我的数据帧的一列而不是 ...

  5. python两个字符串数据可以复制吗_无论如何,是否要将Python pandas数据框中的单个数据中的数据复制到字符串或列表中以进行进一步处理?...

    使用示例数据.请注意,由于复制和粘贴选项卡占用空格(因此使用sep ='\ s +',iso'\ t')并且我已将数据的第一行设置为列名(不使用header = None).可以使用join将一列连接 ...

  6. json pandas 内存溢出_python-将多个JSON记录读取到Pandas数据框中

    注意:str.join(自0.19.0开始)现在支持行分隔的json: In [31]: pd.read_json('{"a":1,"b":2}\n{" ...

  7. python怎么选取不连续的列_python – Pandas从数据帧中选择不连续的列

    如果要连接df列的子选择,请使用pd.concat: pd.concat([comb.ix[:,0:1],comb.ix[:,17:342]], axis=1) 只要索引匹配,那么这将正确对齐. 感谢 ...

  8. pandas数据框loc属性语法及示例

    pandas.DataFrame.loc[] 是数据框的属性,通过指定标签或布尔数组来访问数据框的一组行和列.pandas.DataFrame是带有轴标签的二维表数据结构,如列和行.从数据框选择列结果 ...

  9. 熊猫数据集_处理熊猫数据框中的列表值

    熊猫数据集 Have you ever dealt with a dataset that required you to work with list values? If so, you will ...

最新文章

  1. php 分页类使用,php 分页类
  2. MySQL 高级 - 存储过程 - 语法 - if判断 || 传递参数 (IN - 输入 OUT-输出)
  3. OpenCV图像处理使用笔记(八)——Sobel算子
  4. 全球及中国汽车维修行业发展战略规划及投资策略建议报告2021-2027年
  5. 我是程序员,每一天都太难了!
  6. 结构体自动化转为char数组的实现
  7. ModuleNotFoundError: No module named 'tinymce
  8. altera fpga sdi输出方案_FPGA在电力电子中的应用有哪些?
  9. 代码的坏味道:控制结构嵌套太深
  10. python脚本绘图_python实现画图工具
  11. nginx 访问控制之 document_uri
  12. 企业如何选择一个合适的可视化工具
  13. C# 在数组中判断是否存在某个数组值
  14. 如何在 Mac 上的“音乐”应用和 iTunes 中创建 Genius 播放列表?
  15. android多线程中更新ui,Android 在子线程中更新UI
  16. 牛奶盒喷码字符识别(基于opencv)————(三)字符的识别
  17. echarts中国地图,设置地图外边框,内各省界线不同样式
  18. LAYUI 树形表格(tree table)
  19. 如何搭建自己的CI/CD平台:Gitlab+Jenkins+Docker+Harbor+K8s集群搭建CICD平台(持续集成部署Hexo博客Demo)
  20. 数据结构实现排队系统

热门文章

  1. 在eclipse中安装groovy插件详细步骤
  2. 【程序员跳槽】学弟被高薪挖走不到一年就后悔的无奈经历,到底是老板的水深?还是学弟太年轻?
  3. Android面试题目之(9) 幽灵引用
  4. 算法---------两个数的交集
  5. android 启动速度优化终极方案
  6. 【Android】Android中使用JNI调用底层C++代码
  7. 利用归并排序求逆序对
  8. 继承SectionIndexer,实现联系人侧边栏
  9. 机器学习——详解KD-Tree原理
  10. Android App压力测试(Monkey和ADB)