For循环返回DataFrame中的唯一值

我正在研究一个初学者的 ML 代码,为了计算一列中唯一样本的数量,作者使用了以下代码:


def unique_vals(rows, col):

    """Find the unique values for a column in a dataset."""

    return set([row[col] for row in rows])

但是,我正在使用 DataFrame,对我来说,此代码返回单个字母:'m'、'l' 等。我尝试将其更改为:


set(row[row[col] for row in rows)

但随后它返回:


KeyError: "None of [Index(['Apple', 'Banana', 'Grape'   dtype='object', length=2318)] are in the [columns]"

谢谢你的时间!


皈依舞
浏览 199回答 2
2回答

收到一只叮咚

一般来说,你不需要自己做这些事情,因为pandas已经为你做了。在这种情况下,您需要的是unique方法,您可以Series直接在 a 上调用该方法(pd.Series除其他外,它是表示列的抽象),并返回一个numpy包含该中唯一值的数组Series。如果您想要多个列的唯一值,您可以执行以下操作:which_columns = ... # specify the columns whose unique values you want hereuniques = {col: df[col].unique() for col in which_columns}

一只甜甜圈

如果您正在处理分类列,那么以下代码非常有用它不仅会打印唯一值,还会打印每个唯一值的计数col = ['col1', 'col2', 'col3'...., 'coln']#Print frequency of categoriesfor col in categorical_columns:    print ('\nFrequency of Categories for varible %s'%col)    print (bd1[col].value_counts())例子:df     pets     location     owner0     cat    San_Diego     Champ1     dog     New_York       Ron2     cat     New_York     Brick3  monkey    San_Diego     Champ4     dog    San_Diego  Veronica5     dog     New_York       Roncategorical_columns = ['pets','owner','location']#Print frequency of categoriesfor col in categorical_columns:    print ('\nFrequency of Categories for varible %s'%col)    print (df[col].value_counts())输出:# Frequency of Categories for varible pets# dog       3# cat       2# monkey    1# Name: pets, dtype: int64# Frequency of Categories for varible owner# Champ       2# Ron         2# Brick       1# Veronica    1# Name: owner, dtype: int64# Frequency of Categories for varible location# New_York     3# San_Diego    3# Name: location, dtype: int64
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python