gpt4 book ai didi

python - 在分类数据框中查找唯一类值时出错

转载 作者:行者123 更新时间:2023-12-01 07:29:07 24 4
gpt4 key购买 nike

我有一个具有 4 个功能的数据框。

df
A|B|C|D
green|big|1.3|4

现在,我将所有对象特征(A 和 B)放入一个新的数据框中:

df1=df.select_dtypes(include=['object']).columns
df1.dtype
Out: type('O')

最后一步是将 df1 输入到函数中,以确定每个分类特征的唯一值。

for feature in df1.columns:
uniq = np.unique(df1[feature])
print('{}: {} distinct values - {}'.format(feature,len(uniq),uniq))

错误我得到的是:

AttributeError: 'Index' object has no attribute 'columns' when I wanted to get this:

预期输出:

A: 2 distinct values -  ['green' 'blue']
B: 1 distinct values - ['big]

最佳答案

您实际上对 .select_dtypes 行做了一些错误,您已经访问了 .columns。您应该删除它:

df1=df.select_dtypes(include=['object'])  # <i>no</i> .columns

否则,df1 现在是 Index(['A', 'B'], dtype='object')。我们不希望出现这种情况,因为正如错误所述,您无法访问 Index 对象的 .columns

请注意,您可以在此处简单地调用.unique():

for feature in df1.columns:
uniq = df1[feature]<b>.unique()</b>
print('{}: {} distinct values - {}'.format(feature,len(uniq),uniq))

关于python - 在分类数据框中查找唯一类值时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57299128/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com