Python - 计算 Pandas DataFrame 中某一列的标准差


要计算标准差,使用 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() 查找“Units”列值的标准差 −

print"Standard Deviation of Units column from DataFrame1 = ",dataFrame1['Units'].std()

同样,我们从第 2 个 DataFrame 中计算了标准差。

示例

以下是完整代码 −

#
# Python - Calculate the Standard Deviation of column values of a Pandas DataFrame
#

import pandas as pd

# Create DataFrame1
dataFrame1 = pd.DataFrame(
   {
      "Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
      "Units": [100, 150, 110, 80, 110, 90]
   }
)

print"DataFrame1 ...\n",dataFrame1

# Finding Standard Deviation of "Units" column values
print"Standard Deviation of Units column from DataFrame1 = ",dataFrame1['Units'].std()

# Create DataFrame2
dataFrame2 = pd.DataFrame(
   {
      "Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],
      "Price": [8000, 500, 3000, 1500, 3000, 4000]
   }
)

print"\nDataFrame2 ...\n",dataFrame2

# Finding Standard Deviation of "Price" column values
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

更新时间: 15-9 月-2021

666 浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告