![](/img/trans.png)
[英]How to redirect the output of print statement of (if-else) to a text file in Python
[英]How to print a variable name in a print statement or any text output statement. Python, Jupyter Notebook?
這是來自數據集的相關代碼
x = df["var1"]
y = df["var2"]
cor = x.corr(y)
print(f"The Correlation between x and y is: %1.2f"%cor )
Output 將是:
x 和 y 之間的相關性為:-0.22
我希望 output 是:
var1 和 var2 之間的相關性為:-0.22
原因是這些變量會不斷變化,我不想在需要時手動更改它們。 有人能幫忙嗎? 謝謝。
更新
兩個答案都是正確的,取決於您的使用情況。 謝謝@Kei 和@Navid Anjum,如果這對您有幫助,請點贊。
由於您已經在使用 f 字符串,因此我將創建 dataframe 列標題變量,因此每次都會更新打印語句:
x_col = "var1"
y_col = "var2"
x = df[x_col]
y = df[y_col]
cor = x.corr(y)
print(f"The Correlation between {x_col} and {y_col} is: {cor:1.2f}" )
有多種方法可以在字符串中打印變量。 您可以執行以下代碼:
print("The Correlation between "+x+" and "+y+" is: %1.2f"%cor )
或者
print("The Correlation between {} and {} is: {}".format(x,y,cor))
希望這可以幫助
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.