python - 为多个列表创建一个函数并正确分组列表元素
问题描述
我有 3 个列表,但有时只有 2 个,每个列表包含 4 个多索引数据帧。
list1=[df1, df2, df3, df4]
list2=[df1_, df2_, df3_, df4_]
list3=[df1__, df2__, df3__, df4__]
下一步是创建多索引数据框:
reportTable1 = list1[0].round(2) #this dataframe is equal to list1[0], In other words "df1".
reportTable2 = pd.concat([list1[1], list2[1], list3[1]], axis = 0).round(2) #these dataframes have different columns.
reportTable3 = pd.concat([list1[2], list2[2], list3[2]], axis = 0).round(2) #they have same columns.
reportTable4 = pd.concat([list1[3], list2[3], list3[3]], axis = 0).applymap('{:.2%}'.format) #they have same columns.
首先,我想用更简洁的代码为这些步骤定义一个函数。
我的主要问题是在某些情况下list3
不会退出。在这种情况下,我不想出错。list3
在不可用的情况下如何运行此代码?
解决方案
- 如果只有两个
lists
,则以下功能将起作用dataframes
。lists
of以的dataframes
形式传递给函数*args
,因此可以将任意数量的 oflists
传递给函数。
- 类型注释表明
*args
是 alist
ofdataframes
,并且 atuple
ofdataframes
由函数返回。 list(zip(*v))
用于创建正确的dataframes
for组pandas.concat
。- 函数返回的表
t#
的数量对应于 中的dataframes
数量lists
。- 如果
lists
包含的数据帧数量超过了显示的数量(例如df5
,df5_
和df5__
,则在函数中添加一行代码 fort5
andreturn
it.
- 如果
import pandas as pd
from typing import List, Tuple # for type annotations
# function to create report tables
def my_func(*v: List[pd.DataFrame]) -> Tuple[pd.DataFrame]:
l = list(zip(*v)) # use zip to combine the dataframes into the correct groups
t1 = l[0][0].round(2) # l[0] = (df1, df1_, df1__) → l[0][0] = df1
t2 = pd.concat(l[1]).round(2) # l[1] = (df2, df2_, df2__)
t3 = pd.concat(l[2]).round(2) # l[2] = (df3, df3_, df3__)
t4 = pd.concat(l[3]).applymap('{:.2%}'.format) # l[3] = (df4, df4_, df4__)
return t1, t2, t3, t4
# data
l1 = [df1, df2, df3, df4]
l2 = [df1_, df2_, df3_, df4_]
l3 = [df1__, df2__, df3__, df4__]
# function call with 3 lists
rt1, rt2, rt3, rt4 = my_func(l1, l2, l3)
# function call with 2 lists
rt1, rt2, rt3, rt4 = my_func(l1, l2)
推荐阅读
- android - 未捕获的翻译错误:com.android.dx.cf.code.SimException 需要 --min-sdk-version >= 26
- performance - 有没有办法在 Redis on AWS (ElastiCache) 中启用延迟监控阈值?
- rx-java2 - RxJava2 是否需要在 Create() 发射器上尝试/捕获?
- python - 从 SuperClass 访问 Django 子类方法
- excel - Excel 函数宏:创建下拉列表
- sql - 如何获取表中所有列的计数(*)?使用 PostgreSql
- node.js - 安装节点新版本并尝试更新 npm 后 - 在 Windows 中出现错误 MODULE_NOT_FOUND
- git - 使用访问令牌从自己的 bitbucket 服务器克隆 git 存储库会导致端口号错误
- charles-proxy - Charles Proxy:映射到 GET 请求而不是 OPTIONS
- ios - 绘制到 CGContext 时如何设置 UIBezierPath 的线宽?