首页 > 解决方案 > 在 Pandas 中选择数据子集

问题描述

我有一个包含 5 行 × 1317 列的数据集。附上你可以看到数据集的样子。标头包含作为波长的数字。但是我只想从特定波长范围中选择列。我感兴趣的波长数存储在一个大小为 1 × 235 的数组 (c) 中。如何根据存储在 c 中的波长值提取所需的列?

在此处输入图像描述

标签: pythonpandasdataframeheader

解决方案


如果您的数组c仅具有也是列标题的值(即,c没有任何附加值),您可以将其设为列表并使用df[c]c该列表在哪里。

例如,使用当前图片中显示的内容,您可以执行以下操作:

l = [102,105] # I am assuming that your column headings in the df are integers, not strings
df[l]

这将显示这两列。如果你想在某个新的数据框中使用它,然后执行类似df2 = pandas.Dataframe(df[l]) to If l was 5 columns, it would show those 5 columns. And so if you can pass in your arrayc , (or make it into a list, probably by l = list(c)`) 的操作,你将得到你的列

如果您的数组具有附加值,这些值不一定是数据框中的列,则您需要创建一个仅包含这些列的子列表。

sub_c = list() #create a blank list that we will add to
c_list = list(c)
for column in df.columns:
    if column in c_list: sub_c.append(column)
df[sub_c]

这将使该子列表仅具有列标题的值,因此您希望尝试查看不存在的列。

请记住,您需要在c数组和列标题之间匹配数据类型。


推荐阅读