For 循环返回 DataFrame 中的唯一值

Ser*_*ene 1 python pandas

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

def unique_vals(rows, col):
    """Find the unique values for a column in a dataset."""
    return set([row[col] for row in rows])
Run Code Online (Sandbox Code Playgroud)

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

set(row[row[col] for row in rows)
Run Code Online (Sandbox Code Playgroud)

但随后它返回:

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

谢谢你的时间!

gmd*_*mds 5

一般来说,您不需要自己做这些事情,因为pandas它们已经为您做了。

在这种情况下,您需要的是一个unique方法,您可以直接调用该方法Series(该pd.Series方法是表示列等的抽象),并返回一个numpy包含该中唯一值的数组Series

如果您想要多列的唯一值,您可以执行以下操作:

which_columns = ... # specify the columns whose unique values you want here

uniques = {col: df[col].unique() for col in which_columns}
Run Code Online (Sandbox Code Playgroud)