向量化 pandas 数据框列表中的函数 [英] Vectorizing a function on a list of pandas dataframes

查看:75
本文介绍了向量化 pandas 数据框列表中的函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我读取了一个excel文件,并将每个选项卡另存为pandas数据框.

I read an excel file and save each tab as a pandas dataframe.

import pandas as pd
xla = pd.ExcelFile("file_name.xlsx")
kl=xla.sheet_names
hf_list=[]
for i in range(len(kl)):   
    hf_list.append(pd.read_excel(xla, i,index_col=0))

我打算计算列表中每个数据帧的排名,因此编写了以下代码.

I intend to compute rank of each dataframe in the list so have written the following code.

def score_card(raw_list):    
    score_list=[]    
    for i in range(len(raw_list)):
        score_list.append(raw_list[i].rank(axis=1))        
    return score_list

score_list=score_card(hf_list)

我想知道是否有一种方法可以对代码进行矢量化处理,并避免score_card函数中的for循环(也可以读取Excel文件). 预先感谢您的宝贵时间.

I was wondering if there is a way to vectorize the code and avoid for loop(s) in the score_card function (and also reading the excel file). Thanks in advance for your time.

推荐答案

如果在sheet_name = None .read_excel.html"rel =" nofollow noreferrer> read_excel 为每个工作表名称获取DataFrame的顺序:

If use parameter sheet_name = None in read_excel get orderdict of DataFrames for each sheetname:

dfs = pd.read_excel("file_name.xlsx", sheet_name = None, index_col=0) 

然后使用列表理解:

score_list = [v.rank(axis=1) for k, v in dfs.items()]

或使用concat创建大的DataFrame:

Or create big DataFrame with concat:

df = pd.concat(dfs.values())

这篇关于向量化 pandas 数据框列表中的函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆