首页 > 解决方案 > 为多个列表创建一个函数并正确分组列表元素

问题描述

我有 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在不可用的情况下如何运行此代码?

标签: pythonpandasfunctiondataframe

解决方案


  • 如果只有两个lists,则以下功能将起作用dataframes
    • listsof以的dataframes形式传递给函数*args,因此可以将任意数量的 oflists传递给函数。
  • 类型注释表明*args是 a listof dataframes,并且 a tupleofdataframes由函数返回。
  • list(zip(*v))用于创建正确的dataframesfor组pandas.concat
  • 函数返回的表t#的数量对应于 中的dataframes数量lists
    • 如果lists包含的数据帧数量超过了显示的数量(例如df5,df5_df5__,则在函数中添加一行代码 for t5and returnit.
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)

推荐阅读