亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅識別數據框中列中的數值 - 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 關注
  • 198 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號