Python - 计算 Pandas DataFrame 中某一列的标准差
pythonserver side programmingprogramming更新于 2025/10/29 14:36:17
要计算标准差,请使用 Pandas 的 std() 方法。首先,导入所需的 Pandas 库 −
import pandas as pd
现在,创建一个包含两列的 DataFrame −
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90] }
)
查找"单位"的标准差使用 std() 计算列值 −
print"Standard Deviation of Units column from DataFrame1 = ",dataFrame1['Units'].std()
以同样的方式,我们计算了第二个 DataFrame 的标准差。
示例
以下是完整代码 −
#
# Python - 计算 Pandas DataFrame 列值的标准差
#
import pandas as pd
# 创建 DataFrame1
dataFrame1 = pd.DataFrame(
{
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
print"DataFrame1 ...\n",dataFrame1
# 查找"Units"列值的标准偏差
print"Standard Deviation of Units column from DataFrame1 = ",dataFrame1['Units'].std()
# 创建 DataFrame2
dataFrame2 = pd.DataFrame(
{
"Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],
"Price": [8000, 500, 3000, 1500, 3000, 4000]
}
)
print"\nDataFrame2 ...\n",dataFrame2
# 查找"Price"列值的标准差
print"Standard Deviation of Price column from DataFrame2 = ",dataFrame2['Price'].std()
输出
这将产生以下输出 −
DataFrame1 ... Car Units 0 BMW 100 1 Lexus 150 2 Audi 110 3 Tesla 80 4 Bentley 110 5 Jaguar 90 Standard Deviation of Units column from DataFrame1 = 24.2212028328 DataFrame2 ... Price Product 0 8000 TV 1 500 PenDrive 2 3000 HeadPhone 3 1500 EarPhone 4 3000 HDD 5 4000 SSD Standard Deviation of Price column from DataFrame2 = 2601.28173535
相关文章
有用资源
python 参考教程 - 该教程包含有关 python 的更多信息:https://www.cainiaomax.com/python/

