Python读入Excel的xlsx文件 corr相关系数 对向量和矩阵进行softmax

Python读入Excel的xlsx文件 corr相关系数 对向量和矩阵进行softmax

  • 方法1:利用pandas
  • 方法2:利用xlrd
#-------方法一-------:
import pandas as pd

#其中filePath是读入xlsx文件的路径
filePath = "C:/Users/MD.xlsx"
data = pd.read_excel(filePath)#得到的data是DateFrame类型,可利用pandas进行变换

#-------方法二-------:
import xlrd
import pandas as pd

filePath = "C:/Users/MD.xlsx"
sheets = xlrd.open_workbook(filePath)

#查看所有sheet表名称
#print(sheets.sheet_name())

#获取不同的sheet表
sheet1 = sheets.sheet_by_index(0)#获取第一张sheet表
#sheet2 = sheets.sheet_by_index(1)#获取第二张sheet表
#sheet2_name = sheet2.name#查看第二张sheet表名称

rows = sheet1.rows#获取总行数
cols = sheet1.cols#获取总列数
#print(rows, cols)#打印总行数、总列数

#col1 = sheet1.col_values(0)#拿出第一张sheet的第一列
#col2 = sheet1.col_values(1)#拿出第一张sheet的第二列
#打印第一张sheet所有的行
for i in range(0, rows):
	print(sheet1.row_values(i))
for j in range(0, cols):
	print(sheet1.col_values(j))

#-------------------------写入csv文件---------------------------
fileSavePath = "C:/Users/haha/Desktop/save.csv"
with open(filename, 'w', newline='') as f:
    write = csv.writer(f)
    for i in range(rows):
        temp = zsheet2.row_values(i)
        write.writerow(temp)
print("写入csv文件完毕!")

#---------------------将前面读入进来的data写到csv和xlsx文件----------
#写入到csv
data.to_csv("C:/Users/haha/Desktop/save1.csv", sep='\t', index = True, header = True)

#写入到xlsx
data.to_excel("C:/Users/haha/Desktop/save.xlsx", index = True, header = True)

相关系数

#对上述代码块的data数据中的数值列进行相关系数分析。此处用秩相关系数
#corr一共有3中相关系数求解方法,有兴趣的可自行查阅相关资料
correlation = data.corr(method = "spearman')#得到一个对称矩阵

对矩阵或者向量进行softmax。【从别处转载】

import numpy as np

def softmax(x):
    """
    对输入x的每一行计算softmax。

    该函数对于输入是向量(将向量视为单独的行)或者矩阵(M x N)均适用。
    
    代码利用softmax函数的性质: softmax(x) = softmax(x + c)

    参数:
    x -- 一个N维向量,或者M x N维numpy矩阵.

    返回值:
    x -- 在函数内部处理后的x
    """
    orig_shape = x.shape

    # 根据输入类型是矩阵还是向量分别计算softmax
    if len(x.shape) > 1:
        # 矩阵
        tmp = np.max(x, axis = 1) # 得到每行的最大值,用于缩放每行的元素,避免溢出。 shape为(x.shape[0],)
        x -= tmp.reshape((x.shape[0],1)) # 利用性质缩放元素
        x = np.exp(x) # 计算所有值的指数
        tmp = np.sum(x, axis = 1) # 每行求和        
        x /= tmp.reshape((x.shape[0], 1)) # 求softmax
    else:
        # 向量
        tmp = np.max(x) # 得到最大值
        x -= tmp # 利用最大值缩放数据
        x = np.exp(x) # 对所有元素求指数        
        tmp = np.sum(x) # 求元素和
        x /= tmp # 求somftmax
    return x

# x = np.array([[1,2,3],[4,7,6]])
x = np.array([1,2,3])
print(softmax(x))
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值