python - 如何在列上添加标题

标签 python pandas dataframe

如何将列添加到数据框 xFlattened ?就我而言,xFlattened.columns 没有帮助我。

def corrFilter(x, bound):
    xCorr = x.corr()
    xFiltered = xCorr[((xCorr >= bound) | (xCorr <= -bound)) & (xCorr !=1.000)]
    xFlattened = xFiltered.unstack().sort_values(ascending = False).drop_duplicates()
    xFlattened.columns = ["first_value", "second_value", "corr"]
    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)

df = corrFilter(df, .7)
df

我想要什么

             first_value              second_value      percentage
0 review_scores_accuracy      review_scores_rating        0.968217
1                           review_scores_accuracy             NaN

最佳答案

您需要在函数中添加 reset_index 才能将 Series 转换为 DataFrame:

xFlattened = xFiltered.unstack().sort_values(ascending = False).drop_duplicates().reset_index()

输出:

              first_value            second_value      corr
0  review_scores_accuracy    review_scores_rating  0.968217
1  review_scores_accuracy  review_scores_accuracy       NaN

关于python - 如何在列上添加标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70025732/

相关文章:

python - 在某些条件下分割数据框

python - 将分组的 pandas DataFrame 转换为 3 维数组以进行序列预测

python - Spark 创建数据帧,其中包含整数和 float 混合的列

python - 这与图切边(桥)有关吗?及时找到从家到商店/商店的快速路径

python - 检测和更改 PDF 中的字符串

python - PyQt 窗口打开后立即关闭

python - 如何将两个字符串转换成单个字典?

python - Pandas - 基于 bool DataFrame 替换 DataFrame 中的值

python - 在 pandas 中用 NaN 替换空白值(空白)

python - 在 Pandas 中计算奇数比的更好方法