首頁  >  文章  >  後端開發  >  python123的溫度轉換怎麼寫

python123的溫度轉換怎麼寫

下次还敢
下次还敢原創
2024-03-29 06:07:19445瀏覽

Python 提供多種轉換溫度單位的方法:使用NumPy庫中的numpy.convert_units()函數:導入NumPy,使用convert_units進行轉換。使用Pandas庫中的pandas.to_numeric()函數:導入Pandas,使用to_numeric智慧轉換溫度。使用自訂函數:建立自訂函數fahrenheit_to_celsius和celsius_to_fahrenheit進行轉換。

python123的溫度轉換怎麼寫

Python中溫度轉換

Python提供了多種方法來轉換溫度單位:

使用NumPy

NumPy函式庫中的numpy.convert_units()函數可用來轉換溫度單位:

<code class="python">import numpy as np

# 从华氏度转换为摄氏度
celsius = np.convert_units(100, 'degF', 'degC')

# 从摄氏度转换为华氏度
fahrenheit = np.convert_units(37, 'degC', 'degF')</code>

#使用Pandas

Pandas庫中的pandas.to_numeric()函數可以智慧地轉換溫度單位:

<code class="python">import pandas as pd

# 从华氏度转换为摄氏度
celsius = pd.to_numeric("100 degF", unit='degF', errors='coerce')

# 从摄氏度转换为华氏度
fahrenheit = pd.to_numeric("37 degC", unit='degC', errors='coerce')</code>

使用自訂函數

#也可以建立自訂函數來轉換溫度單位:

<code class="python">def fahrenheit_to_celsius(fahrenheit):
    """将华氏度转换为摄氏度"""
    return (fahrenheit - 32) * 5/9

def celsius_to_fahrenheit(celsius):
    """将摄氏度转换为华氏度"""
    return celsius * 9/5 + 32</code>

範例

#以下是如何使用這些方法轉換溫度單位:

<code class="python"># NumPy
fahrenheit_value = 100
celsius_value = np.convert_units(fahrenheit_value, 'degF', 'degC')
print("华氏度:", fahrenheit_value, "摄氏度:", celsius_value)

# Pandas
fahrenheit_value = "100 degF"
celsius_value = pd.to_numeric(fahrenheit_value, unit='degF', errors='coerce')
print("华氏度:", fahrenheit_value, "摄氏度:", celsius_value)

# 自定义函数
fahrenheit_value = 100
celsius_value = fahrenheit_to_celsius(fahrenheit_value)
print("华氏度:", fahrenheit_value, "摄氏度:", celsius_value)</code>

以上是python123的溫度轉換怎麼寫的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn