有没有办法在 Pandas 中获取所有分类变量?我知道的最好的方法是遍历所有列并检查它是否dtype是分类的。
最终,我想要一个单线来绘制所有分类变量的所有条形图。
使用select_dtypes并传递 the'category'作为过滤 df 的类型,这将返回dtype与此匹配的所有列:
In [9]:
df = pd.DataFrame({'a': np.random.randn(6),
'b': [True, False] * 3,
'c': [1.0, 2.0] * 3})
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 6 entries, 0 to 5
Data columns (total 3 columns):
a 6 non-null float64
b 6 non-null bool
c 6 non-null float64
dtypes: bool(1), float64(2)
memory usage: 150.0 bytes
In [10]:
df['a'] = pd.Categorical(df['a'])
df['c'] = pd.Categorical(df['c'])
df.info()
<class 'pandas.core.frame.DataFrame'>
Int64Index: 6 entries, 0 to 5
Data columns (total 3 columns):
a 6 non-null category
b 6 non-null bool
c 6 non-null category
dtypes: bool(1), category(2)
memory usage: 130.0 bytes
In [11]:
df.select_dtypes(['category'])
Out[11]:
a c
0 1.295878 1
1 -1.230722 2
2 0.340209 1
3 -0.277246 2
4 -2.336386 1
5 0.363829 2
Run Code Online (Sandbox Code Playgroud)
小智 5
catCols = [col for col in df.columns if df[col].dtype=="O"]
Run Code Online (Sandbox Code Playgroud)
catcols 是一个列表,将包含 df 中类型为 O 的所有列,即对象
| 归档时间: |
|
| 查看次数: |
6239 次 |
| 最近记录: |