筛选一列中字母、数字或连字符的行

2024-09-28 05:27:39 发布

您现在位置:Python中文网/ 问答频道 /正文

给定如下数据帧,我需要检查room列:

   id    room
0   1   A-102
1   2     201
2   3    B309
3   4   C·102
4   5  E_1089

此列的正确格式应为numbersalphabethyphen,否则,用incorrect填充check

预期结果如下:

   id    room      check
0   1   A-102        NaN
1   2     201        NaN
2   3    B309        NaN
3   4   C·102  incorrect
4   5  E_1089  incorrect

这里的非正式语法可以是:

df.loc[<filter1> | (<filter2>) | (<filter3>), 'check'] = 'incorrect'

提前谢谢你的帮助


Tags: 数据iddfcheck格式语法nanloc
1条回答
网友
1楼 · 发布于 2024-09-28 05:27:39

使用str.match强制所有字符:

df['check'] = np.where(df.room.str.match('^[a-zA-Z\d\-]*$'), np.NaN, 'incorrect')

str.contains带否定模式:

df['check'] = np.where(df.room.str.contains('([^a-zA-Z\d\-])'), 'incorrect', np.NaN)

输出:

   id    room      check
0   1   A-102        nan
1   2     201        nan
2   3    B309        nan
3   4   C·102  incorrect
4   5  E_1089  incorrect

如果要更新现有的check列,请使用loc访问。例如:

df.loc[df.room.str.contains('([^a-zA-Z\d\-])'), 'check'] = 'incorrect'
# or safer when `NaN` presents
# df.loc[df.room.str.contains('([^a-zA-Z\d\-])') == True, 'check'] = 'incorrect'

相关问题 更多 >

    热门问题