【问题标题】:python: undetected categorical valuespython:未检测到的分类值
【发布时间】:2021-07-10 10:53:34
【问题描述】:

我想找出数据框的哪些列是分类的。 这个数据框确实有 z 列,但我的代码无法检测到它并打印一个空列表。 我该如何解决?

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

data=[[ 10,10,'a'],
    [ 15,15,'a'],
    [ 14,14,'b']
    ,[16,16,'b'],
    [19,19,'a'],
    [17,17,'a']
    ,[6,6,'c'],
    [5,5,'b'],
    [20,20,'c']
    ,[22,22,'c'],
    [21,21,'b'],
    [18,45 ,'a']]
df = pd.DataFrame(data, columns=['x','y','z'])
categorical_values=[]
for i in df.columns.values.tolist():
    if (type(df[i].all()))==str:
        categorical_values.append(i)

print(categorical_values, 'CATEGORICAL VALUES')
print(len(categorical_values),'total of categorical variables')

【问题讨论】:

  • 无法复制,打印 ['z'] CATEGORICAL VALUES1 total of categorical variables (pandas 1.2.1, numpy 1.19.1)
  • 这能回答你的问题吗? stackoverflow.com/a/65569109/16310106
  • 使用 (dataframe.column.dtype) 获取列的类型,然后将其与您要查找的所需类型进行比较。

标签: python pandas dataframe categorical-data


【解决方案1】:

这里似乎有问题的是你的测试if (type(df[i].all()))==str,让我们分解它:

  • 获取列i
  • 检查该列的所有值是否为True,参见the doc for .all()

    Series.all(axis=0, bool_only=None, skipna=True, level=None, **kwargs)

    返回是否所有元素都为真,可能在轴上。

    除非在一个系列中或沿 Dataframe 轴至少有一个元素为 False 或等效(例如零或空),否则返回 True。

  • 获取返回类型
  • 检查此类型是否为str

您似乎想检查列的数据类型。为此,请使用dtypes

>>> df.dtypes
x     int64
y     int64
z    object

您甚至可以直接从数据框中select dtypes

>>> df.select_dtypes(include=['object'])
    z
0   a
1   a
2   b
3   b
4   a
5   a
6   c
7   b
8   c
9   c
10  b
11  a
>>> categorical_values = df.select_dtypes(include=['object']).columns.to_list()
>>> categorical_values
['z']

【讨论】:

    猜你喜欢
    • 2018-11-05
    • 2021-05-04
    • 2017-09-23
    • 2021-06-18
    • 1970-01-01
    • 2020-08-09
    • 1970-01-01
    • 1970-01-01
    • 2022-08-06
    相关资源
    最近更新 更多