You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何提取星体数据的Object与Filter字段并去重Object?代码报错求助

解决星体数据展示的AttributeError问题并实现需求

错误原因分析

你遇到的 AttributeError: '_io.TextIOWrapper' object has no attribute 'loc' 是因为直接对打开的文件对象调用了pandas的loc方法——loc是pandas DataFrame特有的属性,而文件对象(_io.TextIOWrapper)根本没有这个方法。必须先把文件中的数据读取成结构化的DataFrame(或其他数据结构)才能处理。

实现需求的两种方案

需求核心是:展示Object和Filter字段,且不重复显示Object(让同个星体的所有Filter归为一组)。以下提供两种可行方案:

方案一:使用Pandas(适合大数据集)

Pandas能高效处理结构化数据,适合批量去重和分组:

import pandas as pd

# 1. 读取数据文件(假设是CSV格式,其他格式用pd.read_excel/pd.read_table)
df = pd.read_csv("星体观测数据.csv")

# 2. 只保留需要的两列
target_cols = df[["Object", "Filter"]]

# 3. 按Object分组,合并对应的Filter(自动去重同个Object下的重复Filter)
grouped_data = target_cols.groupby("Object")["Filter"].apply(lambda x: list(set(x))).reset_index()

# 4. 友好展示结果
for _, row in grouped_data.iterrows():
    print(f"🔭 Object: {row['Object']}")
    print(f"📋 Filters: {', '.join(row['Filter'])}")
    print("------------------------")

# 也可以输出成表格形式(去重后按Object排序)
unique_table = target_cols.drop_duplicates().sort_values(by="Object")
print("\n📊 去重后的表格视图:")
print(unique_table.to_string(index=False))

方案二:原生Python实现(无需第三方库,适合小数据集)

如果不想用Pandas,用字典+集合也能实现需求:

object_filter_map = {}

# 读取文件并处理数据(假设是逗号分隔的文本文件)
with open("星体观测数据.txt", "r", encoding="utf-8") as f:
    # 读取表头,定位Object和Filter的列索引
    header = f.readline().strip().split(",")
    obj_col = header.index("Object")
    filter_col = header.index("Filter")
    
    # 遍历每行数据
    for line in f:
        line_data = line.strip().split(",")
        obj_name = line_data[obj_col]
        filter_val = line_data[filter_col]
        
        # 用集合存储Filter,自动去重
        if obj_name not in object_filter_map:
            object_filter_map[obj_name] = set()
        object_filter_map[obj_name].add(filter_val)

# 输出结果
for obj, filters in object_filter_map.items():
    print(f"🔭 Object: {obj}")
    print(f"📋 Filters: {', '.join(filters)}")
    print("------------------------")

关键说明

  • 如果你的数据文件不是CSV/逗号分隔,需要调整读取逻辑(比如空格分隔就用split(),制表符分隔用split("\t"))。
  • 两种方案都会自动处理Object重复的问题,同个星体的所有Filter会被归到一起,避免逐行重复阅读。

内容的提问来源于stack exchange,提问作者Zulyani R

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 09:05:15