【问题标题】:Using the Python WITH statement to create temporary variable使用 Python WITH 语句创建临时变量
【发布时间】:2020-08-02 04:04:12
【问题描述】:

假设我有 Pandas 数据。任何数据。我导入seaborn 来制作变量之间相关性的彩色版本。除了将相关表达式传递给热图函数,也不是创建一次性变量来存储相关输出,我如何使用with 语句创建在绘制热图后不再存在的临时变量?

不起作用

# Assume: season = sns, Data is heatmapable
with mypandas_df.correlation(method="pearson") as heatmap_input:
    # possible other statements
    sns.heatmap(heatmap_input)
    # possible other statements

如果存在,那么在 seaborn 绘制地图后,heatmap_input 不再作为变量存在。我想要 tat 功能。

任重道远

# this could be temporary but is now global
tcbtbing = mypandas_df.correlation(method="pearson")
sns.heatmap(tcbtbing)

紧凑的方式

sns.heatmap( mypandas_df.correlation(method="pearson") )

我想使用with 语句(或类似的short)构造来避免Long Way 和Compact 方式,但为其他操作留出空间,例如情节本身.

【问题讨论】:

    标签: python-3.x pandas with-statement


    【解决方案1】:

    您需要为要使用的类实现 enterexit。 见:Implementing use of 'with object() as f' in custom class in python

    【讨论】:

    • 哇。这看起来相当可怕。感谢您的洞察力。不过,这太冗长了。特别是因为我没有在我自己的自定义对象上使用它。
    猜你喜欢
    • 2022-12-03
    • 1970-01-01
    • 2020-12-06
    • 2016-12-07
    • 2012-02-28
    • 1970-01-01
    • 2017-09-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多