【问题标题】:Errors for finding unique class values within categorical dataframe在分类数据框中查找唯一类值的错误
【发布时间】:2019-07-31 21:33:08
【问题描述】:

我有一个具有 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 want to get this:

预期输出

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

【问题讨论】:

  • 你应该看看unique
  • 您已经将df1 设置为列。

标签: python pandas


【解决方案1】:

您实际上对.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].unique()
    print('{}: {} distinct values -  {}'.format(feature,len(uniq),uniq))

【讨论】:

  • @Willen Van Onsem,如果我想排除一些对象列,我将如何在 df1=df.select_dtypes(include=['object']) 中具体说明这一点?
猜你喜欢
  • 2017-11-10
  • 1970-01-01
  • 1970-01-01
  • 2018-07-17
  • 1970-01-01
  • 2021-08-18
  • 2020-04-09
  • 1970-01-01
  • 2020-03-05
相关资源
最近更新 更多