【发布时间】: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 VALUES和1 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