python - 在 Pandas 中选择数据子集
问题描述
我有一个包含 5 行 × 1317 列的数据集。附上你可以看到数据集的样子。标头包含作为波长的数字。但是我只想从特定波长范围中选择列。我感兴趣的波长数存储在一个大小为 1 × 235 的数组 (c) 中。如何根据存储在 c 中的波长值提取所需的列?
解决方案
如果您的数组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 array
c , (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
数组和列标题之间匹配数据类型。
推荐阅读
- c# - 如何使用不在上下文中的 linq-query 获取实体?
- c++ - 提取运算符错误地读入 0,但在类似情况下读入正确的数字
- kubernetes - 访问由 nginx-ingress 处理的 webapp 的子域
- java - DBUnit:NoSuchColumnException ColumnNameToIndexes 缓存映射中的非大写输入列。地图的列名不区分大小写
- python - 无法将 PDF 转换为文本格式
- angular - 我需要单元测试方面的帮助。对于代码。我想通过编写单元测试在角度规范文件中覆盖这段代码
- android - 在android构建上找不到本机库?
- r - 如何拆分混合大小写的字符串?
- android - 为什么每次重新启动应用程序时都会创建数据库?
- regex - awk 或 sed:如何根据上一行和下一行进行修改