python - 无法解释“CategoricalDtype”
问题描述
我想将变量分成不同的类型。例如:
Tweets ID Registration Date num_unique_words photo_profile range
object int64 object float64 int64 category
我所做的是:
type_dct = {str(k): list(v) for k, v in df.groupby(df.dtypes, axis=1)}
但我有一个 TypeError:
TypeError: Cannot interpret 'CategoricalDtype(categories=['<5',
'>=5'], ordered=True)' as a data type
range
可以取两个值:'<5' 和 '>=5'。
我希望你能帮助处理这个错误。
df = pd.DataFrame({'Tweets': ['Tweet 1 from user 1', 'Tweet 2 from user 1',
'Tweet 1 from user 3', 'Tweet 10 from user 1'],
'ID': [124, 124, 12, 124],
'Registration Date': ['2020-12-02', '2020-11-21',
'2020-12-02', '2020-12-02'],
'num_unique_words': [41, 42, 12, 69],
'photo_profile': [1, 0, 1, 1],
'range': ['<5', '<5', '>=5', '<5']},
index=['falcon', 'dog', 'spider', 'fish'])
解决方案
更新:
这比我想象的要复杂得多,但这里有一个使用列表理解的解决方法:
type_dct = {str(k): list(v) for k, v in df.groupby([i.name for i in df.dtypes], axis=1)}
输出:
{'category': ['range'],
'int64': ['ID', 'num_unique_words', 'photo_profile'],
'object': ['Tweets', 'Registration Date']}
pd.CategorialDtypes 本身在 groupby 中不能很好地工作,我们必须使用该对象的 name 属性。
来自文档的示例。
df = pd.DataFrame({'a': [1, 2] * 3,
'b': [True, False] * 3,
'c': [1.0, 2.0] * 3})
df
a b c
0 1 True 1.0
1 2 False 2.0
2 1 True 1.0
3 2 False 2.0
4 1 True 1.0
5 2 False 2.0
df.select_dtypes(include='bool')
b
0 True
1 False
2 True
3 False
4 True
5 False
df.select_dtypes(include=['float64'])
c
0 1.0
1 2.0
2 1.0
3 2.0
4 1.0
5 2.0
df.select_dtypes(exclude=['int64'])
b c
0 True 1.0
1 False 2.0
2 True 1.0
3 False 2.0
4 True 1.0
5 False 2.0
推荐阅读
- android - Android从PC启用USB调试?
- python - 在 Pygame 中使用 Dirty Rects 会更新整个显示,而不仅仅是矩形
- apache - 当仍有 APACHE 服务器运行时 Gitlab 自托管
- php - 我的 php rooter 正在路由我的 css/jpg... 文件
- batch-file - 使用 7zip 和批处理文件在多个压缩文件中搜索,如果找到结果,请执行某些操作
- jenkins - 如何在groovy中替换yaml文件中的字符串?
- html - 电子邮件中 document.form 的值
- node.js - 数据库更新 Socket.io 时更新 React 状态
- ios - 列出 xCode 组中的所有文件 URL
- ios - 在颤动中生成 Podfile 的正确方法是什么?