【问题标题】:How to make the column of one file as heading of other file's column with pandas in python?python - 如何使用python中的pandas将一个文件的列作为其他文件列的标题?
【发布时间】:2020-05-10 13:20:19
【问题描述】:

我有 3 个 xlsx 文件,分别命名为数据、矢量和标题。

  1. 数据包含 5x5 个条目,this is data dataframe looks
  2. 向量包含 5x1 个条目,this is vector dataframe looks
  3. 标题包含 5x1 条目,this is heading dataframe looks

我从数据文件中取出每一列并找到它与向量的相关性

for i,j in data.iteritems():
col=j
coef, p = spearmanr(col, vector)
alpha = 0.05
if p < alpha:
    print('\n\nSpearmans correlation coefficient: %.3f' % coef)
    print(f' column {[i]} method are correlated (reject H0) p=%.3f' % p)

这给了我输出

Spearmans 相关系数:1.000。 column[0] 方法是相关的(拒绝 H0) p=0.000

Spearmans 相关系数:1.000。 column[2] 方法是相关的(拒绝 H0) p=0.000

Spearmans 相关系数:1.000。 column[3] 方法是相关的(拒绝 H0) p=0.000

我想指向标题的特定列,以便我想要的输出是

Spearmans 相关系数:1.000。红色方法相关(拒绝 H0) p=0.000

Spearmans 相关系数:1.000。绿色方法是相关的(拒绝 H0) p=0.000

Spearmans 相关系数:1.000。蓝色方法是相关的(拒绝 H0)p=0.000

任何参考资料或资源都会有所帮助。 谢谢

【问题讨论】:

    标签: python python-3.x pandas dataframe data-science


    【解决方案1】:

    您需要在打印时使用您的heading 变量。因此,您需要使用{heading.loc[i,0]},而不是使用column {[i]}

    这里是完整的代码:

    import pandas as pd
    from scipy.stats import spearmanr
    
    data = pd.DataFrame([[2, 3, 5, 10, 76],
                         [20, 6, 10, 100, 87],
                         [40, 30, 15, 1000, 46],
                         [60, 9, 20, 10000, 43],
                         [80, 12, 25, 100000, 98]])
    
    vector = pd.DataFrame([[60], [80], [100], [120], [140]])
    heading = pd.DataFrame([['red'], ['orange'], ['green'], ['blue'], ['yellow']])
    
    for i,j in data.iteritems():
        col=j
        coef, p = spearmanr(col, vector)
        alpha = 0.05
        if p < alpha:
            print('\n\nSpearmans correlation coefficient: %.3f' % coef)
            print(f' {heading.loc[i,0]} method are correlated (reject H0) p=%.3f' % p)
    

    它产生以下输出:

    Spearmans correlation coefficient: 1.000
     red method are correlated (reject H0) p=0.000
    
    
    Spearmans correlation coefficient: 1.000
     green method are correlated (reject H0) p=0.000
    
    
    Spearmans correlation coefficient: 1.000
     blue method are correlated (reject H0) p=0.000
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-09-29
      • 1970-01-01
      相关资源
      最近更新 更多