'How does one use an assignment expression in a dictionary comprehension?

Suppose I have the below data frame:

df = pd.DataFrame([
             [100,90,80,70,36,45],
             [101,78,65,88,55,78],
             [92,77,42,79,43,32],
             [103,98,76,54,45,65]],
             index = pd.date_range(start='2022-01-01', periods=4)
    )
   
    df.columns = pd.MultiIndex.from_tuples(
            (("mkf", "Open"),
             ("mkf", "Close"),
             ("tdf", "Open"),
             ("tdf","Close"),
             ("ghi","Open"),
             ("ghi", "Close"))
   )

And then I execute the following dictionary comprehension:

{c:df[c].assign(r=np.log(df[(c, 'Close')]).diff()) for c in df.columns.levels[0]}

{'ghi':             Open  Close         r
 2022-01-01    36     45       NaN
 2022-01-02    55     78  0.550046
 2022-01-03    43     32 -0.890973
 2022-01-04    45     65  0.708651,
 'mkf':             Open  Close         r
 2022-01-01   100     90       NaN
 2022-01-02   101     78 -0.143101
 2022-01-03    92     77 -0.012903
 2022-01-04   103     98  0.241162,
 'tdf':             Open  Close         r
 2022-01-01    80     70       NaN
 2022-01-02    65     88  0.228842
 2022-01-03    42     79 -0.107889
 2022-01-04    76     54 -0.380464}

How would one produce the same result with an assignment expression (i.e. the symbol := )?

https://www.digitalocean.com/community/tutorials/how-to-use-assignment-expressions-in-python



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source