Python - 计算 Pandas DataFrame 中列的方差
要计算列值的方差,请使用var()方法。首先,导入所需的 Pandas 库 -
import pandas as pd
创建一个包含两列的 DataFrame -
dataFrame1 = pd.DataFrame({
"Car": ['BMW', 'Lexus', 'Audi', 'Tesla', 'Bentley', 'Jaguar'],
"Units": [100, 150, 110, 80, 110, 90]
}
)
使用var()函数查找“单位”列值的方差-
print"Variance of Units column from DataFrame1 = ",dataFrame1['Units'].var()
以同样的方式,我们计算了第二个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 Variance of "Units" column values
print"Variance of Units column from DataFrame1 = ",dataFrame1['Units'].var()
# Create DataFrame2
dataFrame2 = pd.DataFrame(
{
"Product": ['TV', 'PenDrive', 'HeadPhone', 'EarPhone', 'HDD', 'SSD'],
"Price": [8000, 500, 3000, 1500, 3000, 4000]
}
)
print"\nDataFrame2 ...\n",dataFrame2
# Finding Variance of "Price" column values
print"Variance of Price column from DataFrame2 = ",dataFrame2['Price'].var()
这将产生以下输出 -
DataFrame1 ...Car Units
0 BMW 100
1 Lexus 150
2 Audi 110
3 Tesla 80
4 Bentley 110
5 Jaguar 90
Variance of Units column from DataFrame1 = 586.666666667
DataFrame2 ...
Price Product
0 8000 TV
1 500 PenDrive
2 3000 HeadPhone
3 1500 EarPhone
4 3000 HDD
5 4000 SSD
Variance of Price column from DataFrame2 = 6766666.66667
以上是 Python - 计算 Pandas DataFrame 中列的方差 的全部内容, 来源链接: utcz.com/z/359368.html