pandas 如何选择数据框中的特定列?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51000826/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-14 05:43:48  来源:igfitidea点击:

How to choose specific columns in a dataframe?

pythonpandasdataframe

提问by DevanshuMishra

I have a dataframe with 25 columns and an array([ 2, 4, 8, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 22, 23], dtype=int64). I want to choose some specific columns from the dataframe whose indices are given by the elements of the array and store them in a new dataframe(say df1). So for example,the new dataframe, will have the 2nd, 4th,....23rd column of the original data frame.

我有一个包含 25 列的数据框和一个数组 ([ 2, 4, 8, 10, 11, 12, 13, 14, 17, 18, 19, 20, 21, 22, 23], dtype=int64)。我想从数据框中选择一些特定的列,这些列的索引由数组的元素给出,并将它们存储在一个新的数据框中(比如 df1)。因此,例如,新数据框将具有原始数据框的第 2、第 4、....23 列。

采纳答案by Zev

You can use ilocto accomplish this. For example:

您可以使用它iloc来完成此操作。例如:

import pandas as pd

df = pd.DataFrame(
    [np.random.rand(5),np.random.rand(5), np.random.rand(5), np.random.rand(5)]
)

df.iloc[:,[1,3]]

Which outputs:

哪些输出:

    1           3
0   0.883848    0.409460
1   0.537549    0.426643
2   0.825185    0.361043
3   0.039343    0.674435

You may see older answers suggesting .ix(such as the answer in this questionthat I adapted this from) however, that has been deprecated.

您可能会看到较旧的答案暗示.ix(例如我改编自的这个问题中的答案),但是,这已被弃用。