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
如果您嚴格標記YES
for?int
then 使用isnumeric
else,您可以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

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')

TA貢獻1873條經驗 獲得超9個贊
您可以使用.isnumeric()方法:
df3["Result"]?=?df3["ID"].str.isnumeric().apply(lambda?x:?"No"?if?x?==?False?else?"Yes")
添加回答
舉報