python - 获取具有对象或分类数据类型的列名列表
问题描述
我的目标是获取一个列表对象:['assetCode', 'assetName']
,其中内容是Panda.series
基于多个条件检索的 a 的标签。我试过:
tmp3 = datatype[datatype == 'object' | datatype == 'category'].index # extract label from Pandas.series
这给出了错误:TypeError: cannot compare a dtyped [object] array with a scalar of type [bool]
然而,虽然不太优雅,但我能够找到以下两个可行的解决方案:
tmp2 = datatype[datatype == 'object'].index # extract label from Pandas.series
tmp2[0]
'assetCode'
tmp1 = datatype[datatype == 'category'].index # extract label from Pandas.series
tmp1[0]
'assetName'
如何将这两个字符串组合成一个列表对象?有没有比我尝试实现的更好的方法来实现这个目标?
解决方案
设置
df
A B C
0 8 4 2
1 8 8 6
2 8 5 2
datatype = df.dtypes
datatype
A object
B category
C int64
dtype: object
看起来您正在尝试从某些 DataFrame 中选择对象和分类列(此处未显示)。要修复您的代码,请使用:
tmp3 = datatype[(datatype == 'object') | (datatype == 'category')].index.tolist()
tmp3
# ['A', 'B']
由于按位运算符具有更高的优先级,因此您需要在 ORing 掩码之前使用括号。之后,索引工作正常。
要获取列表,请调用.index.tolist()
。
另一个解决方案是select_dtypes
:
df.select_dtypes(include=['object', 'category'])
A B
0 8 4
1 8 8
2 8 5
df.select_dtypes(include=['object', 'category']).columns
# ['A', 'B']
这避免了对中间datatype
系列的需要。
推荐阅读
- css - 如何对 div 中的所有输入标签进行文本缩进?
- python - Python:如何使用具有部分值熊猫的列合并数据
- python - 检测德语句子中的时态(使用 SpaCy)
- python - 我们可以根据单列数字预测序列中的下一个数字吗?
- java - 如何将本地 Web 应用程序用作 Java 的 UI?
- javascript - Javascript:解析 JSON 对象,同时保留数字键的顺序
- sas - 连接 SAS 中的宏变量以重命名列
- r - 使用 tm 包删除 R 中的停用词时出错
- java - 在 selenium Java 中获取“等待脚本完成超时”,而我没有在脚本中使用任何异步代码
- javascript - Sinon:模拟一个由命名导出调用的内部函数