为了账号安全,请及时绑定邮箱和手机立即绑定

仅识别数据框中列中的数值 - Python

仅识别数据框中列中的数值 - Python

肥皂起泡泡 2024-01-12 10:19:09
我想要一个单独的列,如果“ID ”列包含所有数字值,则返回“是”;如果包含字母或字母数字值,则返回“否”。ID      Result3965      Yeswyq8      NoRO_123    NoCMD_      No2976      Yes
查看完整描述

3 回答

?
拉丁的传说

TA贡献1789条经验 获得超8个赞

你可以pd.Series.str.isnumeric在这里使用。

df['Result'] = np.where(df['ID'].str.isnumeric(), 'YES', 'NO')


       ID Result

0    3965    YES

1    wyq8     NO

2  RO_123     NO

3    CMD_     NO

4    2976    YES

isnumeric使用它不能识别数字有一个警告float。


test = pd.Series(["9.0", "9"])

test.str.isnumeric()


0    False

1     True

dtype: bool

如果您严格标记YESfor intthen 使用isnumericelse,您可以pd.Series.str.fullmatch在此处使用(从版本 1.1.0 开始)。

df['Result'] = np.where(df['ID'].str.fullmatch(r"\d+|\d+\.\d+", 'YES', 'NO')

对于版本<1.1.0,您使用re.fullmatch

df['Result'] = np.where(df['ID'].str.isnumeric(), 'YES', 'NO')


       ID Result

0    3965    YES

1    wyq8     NO

2  RO_123     NO

3    CMD_     NO

4    2976    YES

isnumeric使用它不能识别数字有一个警告float。


test = pd.Series(["9.0", "9"])

test.str.isnumeric()


0    False

1     True

dtype: bool

或者我们可以使用pd.to_numeric布尔掩码pd.Series.isna

m = pd.to_numeric(df['ID'], errors='coerce').isna()
df['Result'] = np.where(m, 'NO', 'YES')

如果errors参数设置为'coerce'无法转换为数字的值,则值将设置为Nan

test = pd.Series(['3965', 'wyq8', 'RO_123', 'CMD_', '2976'])

pd.to_numeric(test)


0    3965.0

1       NaN

2       NaN

3       NaN

4    2976.0

Name: ID, dtype: float64

或者您可以构建自定义函数


def numeric(val):

    try:

        float(val)     # Using just `float` would suffice as int can be 

        return 'YES'   # converted to `float` so both `int`

                       # and `float` wouldnot raise any error

    except ValueError:

        return 'NO'


df['Result'] = df['ID'].apply(numeric)

注意:float也处理科学记数法,float("1e6")-> 1000000.0。


test = pd.Series(['1e6', '1', 'a 10', '1E6'])

test.apply(numeric)


0    YES

1    YES

2     NO

3    YES

dtype: object


查看完整回答
反对 回复 2024-01-12
?
FFIVE

TA贡献1797条经验 获得超6个赞

检查是否ID包含non-digits并使用 反转布尔选择~。使用np.where, 分配选项


df['Result']=np.where(~df.ID.str.contains('(\D+)'),'Yes','N0')


     ID Result

0    3965    Yes

1    wyq8     N0

2  RO_123     N0

3    CMD_     N0

4    2976    Yes

正如@Cameron Riddell 所指出的。您还可以跳过布尔值反转并执行以下操作;


df['Result']=np.where(df.ID.str.contains('(\D+)'),'No','Yes')


查看完整回答
反对 回复 2024-01-12
?
眼眸繁星

TA贡献1873条经验 获得超9个赞

您可以使用.isnumeric()方法:

df3["Result"] = df3["ID"].str.isnumeric().apply(lambda x: "No" if x == False else "Yes")


查看完整回答
反对 回复 2024-01-12
  • 3 回答
  • 0 关注
  • 60 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信