Python Pandas - 从列中获取唯一值
要从 DataFrame 中的列中获取唯一值,请使用unique(). 要计算 DataFrame 中某一列的唯一值,请使用nunique().
首先,导入所需的库 -
import pandas as pd;
创建一个包含 3 列的 DataFrame。我们也有重复的值 -
dataFrame = pd.DataFrame({
"Car": ['BMW', 'Audi', 'BMW', 'Lexus', 'Tesla', 'Lexus', 'Mustang'],"Place": ['Delhi','Bangalore','Hyderabad','Chandigarh','Pune', 'Mumbai', 'Jaipur'],"Units": [100, 150, 50, 110, 90, 120, 80]
}
)
使用计数获取唯一值 -
print"\nUnique values from a column ...\n",dataFrame['Car'].unique()print"\nCount unique values from a column ...\n",dataFrame['Car'].nunique()
示例
以下是代码 -
import pandas as pd;输出结果# create a DataFrame
dataFrame = pd.DataFrame(
{
"Car": ['BMW', 'Audi', 'BMW', 'Lexus', 'Tesla', 'Lexus', 'Mustang'],"Place": ['Delhi','Bangalore','Hyderabad','Chandigarh','Pune', 'Mumbai', 'Jaipur'],"Units": [100, 150, 50, 110, 90, 120, 80]
}
)
print"DataFrame ...\n",dataFrame
# get unique values from a column
print"\nUnique values from a column ...\n",dataFrame['Car'].unique()
print"\nCount unique values from a column ...\n",dataFrame['Car'].nunique()
这将产生以下输出 -
DataFrame ...Car Place Units
0 BMW Delhi 100
1 Audi Bangalore 150
2 BMW Hyderabad 50
3 Lexus Chandigarh 110
4 Tesla Pune 90
5 Lexus Mumbai 120
6 Mustang Jaipur 80
Unique values from a column ...
['BMW' 'Audi' 'Lexus' 'Tesla' 'Mustang']
Count unique values from a column ...
5
以上是 Python Pandas - 从列中获取唯一值 的全部内容, 来源链接: utcz.com/z/349103.html