如果该类别的值计数小于 10,我想用“其他”替换熊猫数据框中的所有类别。
我正在尝试这样的事情。
df['variable'].where(df['variable'].apply(lambda x: x.map(x.value_counts()))<=10, "other")
Run Code Online (Sandbox Code Playgroud)
但我收到以下错误:
AttributeError: 'str' object has no attribute 'map'
Run Code Online (Sandbox Code Playgroud) 目标:转换str为np.ndarray大小bytes1:
import numpy as np
np.array("abc", dtype=[whatever])
Run Code Online (Sandbox Code Playgroud)
没有数据类型的实际结果:array('abc', dtype='<U3')
期望的结果:array([b'a', b'b', b'c'], dtype=[whatever]这让我可以使用切片来获得
我找到但不明白的解决方法:
np.array("abc", dtype='c')
# array([b'a', b'b', b'c'], dtype='|S1')
Run Code Online (Sandbox Code Playgroud)
我通过反复试验发现了这个,认为这'c'可能意味着“char”
我不明白的是:
为什么要dtype='c'这样工作?根据arrays.dtypes 参考,它'c'是“复数浮点”的缩写,而'|S1'是长度为 1 的“零终止字节(不推荐)”。
还直接使用“|S1”作为dtype忽略除第一个字符之外的每个字符,这不是我所期望的,但我想它只是将作为"abc"一个参数,并且b'a'如果仅将单个字节指定为dtype:
np.array("abc", dtype='|S1')
# array(b'a', dtype='|S1')
Run Code Online (Sandbox Code Playgroud)
问题):
dtype='c'这样工作?dtype='c'只是“偶然”工作,那么“正确的方法”是什么?)PS: 是的,有一个np.chararray,但根据链接的文档:
chararray 类的存在是为了向后兼容 Numarray,不建议用于新开发。从 numpy 1.4 开始,如果需要字符串数组,建议使用 dtype object_、string_ …