DataFrame均值结果格式不符,如何保留列名并实现结果拼接?
解决方法
下面几个实用方法能帮你保留原列名,得到方便后续拼接的结构化结果:
方法1:先转DataFrame再转置
计算均值后,用to_frame()把Series转为单列DataFrame,再转置就能还原原列名:
mean_df = BinA_Data.mean(axis=0, skipna=True, numeric_only=True).to_frame().T
这样得到的mean_df会保留原DataFrame的所有列名,每行对应当前文件的均值,后续用pd.concat()就能轻松拼接多个文件的结果。
方法2:直接指定result_type='expand'
在mean()方法里加个参数,直接输出DataFrame格式:
mean_df = BinA_Data.mean(axis=0, skipna=True, numeric_only=True, result_type='expand')
这个参数会让聚合结果直接以DataFrame返回,不用额外转换,列名完全和原数据一致。
方法3:批量处理时直接收集DataFrame
如果是循环处理多个文件,直接把每个文件的均值DataFrame存入列表,最后一次性拼接:
import pandas as pd mean_results = [] for file_path in your_file_list: df = pd.read_csv(file_path) # 根据你的文件类型调整读取方式 # 用上面任意一种方法生成带列名的均值DataFrame single_mean = df.mean(axis=0, skipna=True, numeric_only=True).to_frame().T # 可以加个列标记文件名,方便后续溯源 single_mean['source_file'] = file_path mean_results.append(single_mean) # 拼接所有结果 final_mean_table = pd.concat(mean_results, ignore_index=True)
你之前用transpose()无效是因为直接对Series转置,本质还是Series结构,必须先转成DataFrame再转置才能保留列名。
内容的提问来源于stack exchange,提问作者Rajesh Patel
相关产品推荐
相关产品推荐

