如何在Pandas混合类型列中识别特定整数并生成标记列
解决方案:为混合类型Pandas列创建指定值标记列
现有Pandas DataFrame的specialty列为混合数据类型(包含整数与逗号分隔字符串),数据如下:
0 1,5 1 1 2 1,2,4,6 3 2 4 1 5 1,5 6 3 7 3 8 1 9 2,3
需求是创建新列is_1:当specialty行包含整数1时标记为1,否则为0,预期输出如下:
0 1 1 1 2 1 3 0 4 1 5 1 6 0 7 0 8 1 9 0
可行代码实现
通过np.where()结合str.contains()处理混合类型场景,代码如下:
import numpy as np part_chars['is_1'] = np.where((part_chars['specialty'] == 1) | part_chars['specialty'].str.contains('1'), 1, 0)
逻辑说明
- 针对纯整数行,直接判断是否等于
1 - 针对字符串行,用
str.contains('1')检测是否包含字符1 - 用逻辑或
|合并两个条件,满足任一条件则标记为1,否则为0
内容的提问来源于stack exchange,提问作者hulio_entredas
相关产品推荐
相关产品推荐

