Pandas读取CSV格式文件仅显示表头无内容及合并功能异常问题求助
问题修复说明
核心错误点
- 写入CSV时每行末尾多了一个逗号:表头只有3个字段,每行数据末尾多余的逗号会导致pandas解析时识别到4个字段,触发解析错误,无法正常加载数据
- 列名引用不匹配:表头中压力字段名为
PressureReading,后续统计时错误引用为Pressure reading,会触发KeyError导致程序中断 - 统计逻辑错误:计算最大/最小/平均值时未指定对应列,且平均值运算优先级错误,无法得到正确结果
修复后的完整代码
import pandas as pd # 存储数据到文件1 def RecordData1(): file1 = "dataSensor1.txt" response = "" # 使用with上下文管理器自动处理文件关闭 with open(file1, "w", encoding="utf-8") as outfile: outfile.write("Sensor ID,City,PressureReading") while response != '0': # 若城市名包含空格,可调整输入规则为用逗号分隔,此处保持原有输入逻辑 SensorID, City, PressureReading = input("Enter sensor ID, city and its pressure reading:").split() outfile.write("\n") outfile.write(f"{SensorID},{City},{PressureReading}") response = input("Press enter to continue and zero(0) to exit:") # 存储数据到文件2 def RecordData2(): file2 = "dataSensor2.txt" response = "" with open(file2, "w", encoding="utf-8") as outfile1: outfile1.write("Sensor ID,City,PressureReading") while response != '0': SensorID, City, PressureReading = input("Enter sensor ID, city and its pressure reading:").split() outfile1.write("\n") outfile1.write(f"{SensorID},{City},{PressureReading}") response = input("Press enter to continue and zero(0) to exit:") # 读取并合并两个文件数据 def RetrieveRecord(): df1 = pd.read_csv('dataSensor1.txt', sep=",") df2 = pd.read_csv('dataSensor2.txt', sep=",") print("=====传感器1数据=====") print(df1.to_string()) print("=====传感器2数据=====") print(df2.to_string()) concatrecord(df1, df2) def concatrecord(df1, df2): df3 = pd.concat([df1, df2], ignore_index=True, axis=0) print("=====合并后数据=====") print(df3) # 修正列名引用 max_p = df3['PressureReading'].max() min_p = df3['PressureReading'].min() print(f"最大压力值: {max_p}") print(f"最小压力值: {min_p}") # 修正平均值计算逻辑 avg_p = (max_p + min_p) / 2 print('平均压力读数', avg_p) Filteritem(df3) def Filteritem(df3): choice = input('Please enter Sensor ID to be searched: ') filterItem = df3[df3['Sensor ID'] == choice] print("=====查询结果=====") print(filterItem) if __name__ == "__main__": RecordData1() RecordData2() RetrieveRecord()
额外优化说明
- 改用with上下文管理器处理文件操作,避免异常情况下文件无法正常关闭
- 补充了打印前缀,方便区分不同输出内容
- 调整了字符串拼接逻辑为f-string,可读性更高
- 增加了
if __name__ == "__main__"入口判断,避免模块导入时自动执行逻辑
内容的提问来源于stack exchange,提问作者Omar Solieman
相关产品推荐
相关产品推荐

