能否将变量设置为DataFrame列名,替换为列内高频值?
实现列名自动替换为列内最高频值的方法
完全可以通过pandas内置的统计能力实现需求,核心逻辑是逐列计算非空值的出现频次,取最高频值作为对应列的新名称。
实现步骤
- 加载构造和示例匹配的DataFrame
- 跳过固定标识列(如
id),逐列统计非空值的众数 - 生成新旧列名的映射关系,批量完成重命名
- 清理冗余的无意义列
参考代码
首先导入依赖并构造示例数据:
import pandas as pd import numpy as np data = { "id": ["id1", "id2", "id3", "id4", "id5"], "Col1": [np.nan, np.nan, "volume", np.nan, np.nan], "Col2": [np.nan, "size", "size", np.nan, np.nan], "Col3": ["sample", np.nan, "sample", np.nan, "sample"], "Col4": [np.nan, np.nan, np.nan, "qty", "qty"], "Col5": ["weight", np.nan, np.nan, np.nan, "weight"], "Col...": ["etc", "etc", "etc", "etc", "etc"] } df = pd.DataFrame(data)
注意:统计频次时必须先剔除缺失值,否则
NA会被纳入计数流程,干扰最终结果。
编写列名映射逻辑:
col_mapping = {} for col in df.columns: # 保留原有id列名,不参与重命名 if col == "id": continue # 剔除缺失值后计算众数 non_null_vals = df[col].dropna() if len(non_null_vals) == 0: # 整列为空时保留原列名,避免报错 col_mapping[col] = col continue top_freq_val = non_null_vals.mode()[0] col_mapping[col] = top_freq_val
执行重命名并清理冗余列:
df_result = df.rename(columns=col_mapping) # 移除示例中全为固定值的无意义列 df_result = df_result.drop(columns=["etc"], errors="ignore")
最终输出效果
得到的DataFrame列名会和预期完全一致:
| id | volume | size | sample | qty | weight |
|---|---|---|---|---|---|
| id1 | NaN | NaN | sample | NaN | weight |
| id2 | NaN | size | NaN | NaN | NaN |
| id3 | volume | size | sample | NaN | NaN |
| id4 | NaN | NaN | NaN | qty | NaN |
| id5 | NaN | NaN | sample | qty | weight |
补充说明
- 如果多列的最高频值相同,pandas会自动为重复列名追加序号后缀区分,不会出现列名冲突报错
- 对于存在频次相同的并列最高值的列,
mode()方法会默认返回列表中第一个出现的高频值,可根据需求自定义调整选取规则 - 不需要额外安装第三方库,所有依赖都是pandas原生支持的能力
内容的提问来源于stack exchange,提问作者Harry
相关产品推荐
相关产品推荐

