簡體   English   中英

問:對 pandas 數據幀字典的字典理解,具有多個輸出的 function

[英]Q: Dict comprehension on a dictionary of pandas dataframes, with a function with multiple outputs

我有一個包含 pandas 數據幀和相應鍵的字典:

import pandas as pd
df_dict = pd.read_excel('/directory/data.xlsx', sheet_name=None)

其中鍵是 excel 文件的工作表名稱。

是否可以通過使用具有兩個輸出的 function 來使用字典理解來創建 pandas 數據幀的兩個新字典?

def somefunction(df):
    #Does something
    df1 = df.apply(lambda x: x*2)
    df2 = df.apply(lambda x: x*4)
    return df1, df2

df_dict1, df_dict2 = {key: somefunction(df) for (key, df) in df_dict.items()}
#Does not work..

我知道在使用列表時可以使用zip(*)關鍵字,但它似乎不適用於字典

df_dict1, df_dict2 = zip(*{key: somefunction(df) for (key, df) in df_dict.items()})
#Does not work either

兩者都返回

too many values to unpack (expected 2)

你的字典理解看起來不對。 我認為您正在嘗試執行以下操作:

def somefunction(df):
    #Does something
    df1 = df.apply(lambda x: x*2)
    df2 = df.apply(lambda x: x*4)
    return [df1, df2]

processed_dicts = [list(zip([key]*2, somefunction(df))) for (key, df) in df_dict.items()]
df_dict1 = dict([x[0] for x in processed_dicts])
df_dict2 = dict([x[1] for x in processed_dicts])

您不能 zip 字典,但您可以 zip 他們的項目並從項目列表中構建字典。 在這里你可以這樣做:

[dict(t) for t in zip(*(tuple((key,v)  for v in somefunction(val))
                        for key,val in df_dict.items()))]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM