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

如何为Pandas的xFlattened设置列标题?使用xFlattened.columns不生效怎么解决?

解决方案

问题根因

你操作的xFlattened是带多层索引的Series对象,没有columns属性,因此赋值列名的操作不会生效。

修正后代码

import pandas as pd

def corrFilter(x, bound):
    xCorr = x.corr()
    xFiltered = xCorr[((xCorr >= bound) | (xCorr <= -bound)) & (xCorr != 1.000)]
    # 调用reset_index将Series转为DataFrame,同时把多层索引转换为普通列
    xFlattened = xFiltered.unstack().sort_values(ascending=False).drop_duplicates().reset_index()
    # 按需求重命名列
    xFlattened.columns = ["first_value", "second_value", "percentage"]
    return xFlattened

d = {'review_scores_accuracy': [1.1, 2.0, 4.5, 5.0, 4.9, 4.8, 4.7], 
     'review_scores_rating': [1.1, 2.0, 4.6, 3.9, 4.2, 4.5, 4.2]}
df = pd.DataFrame(data=d)

result = corrFilter(df, .7)
print(result)

输出结果

first_value        second_value  percentage
0  review_scores_accuracy  review_scores_rating    0.968217
1  review_scores_accuracy  review_scores_accuracy         NaN

(注:你示例中第二行first_value为空是pandas控制台输出时自动合并重复值的展示效果,实际数据中该单元格有对应值)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 17:45:05