如果值以數字開頭,我如何創建一個新列(如下所示)來分隔值?我曾嘗試使用 isdigit() 的變體并將值切片以查看第一個字符 [:1],但我無法讓它作業。df.apply(lambda x: x if x['attr'][:1].isdigit()==False)
虛擬資料:
data = {'Name':['Bob','Kyle','Kevin'],
'attr':['abc123','1230','(ab)']}
df = pd.DataFrame(data)
期望的輸出:
data = {'Name':['Bob','Kyle','Kevin'],
'attr':['abc123','1230','(ab)'],
'num_start':[None,'1230',None],
'str_start':['abc123',None,'(ab)']}
df = pd.DataFrame(data)
uj5u.com熱心網友回復:
使用正則運算式:r'^\d'
pandas.Series.str.startswith會作業,除了它不接受正則運算式;相反,使用pandas.Series.str.contains并錨定到字串的開頭^,然后使用 搜索數字\d。
df.attr.str.contains(r'^\d')給出一個Series值True/False;對于它所在的行True,值轉到該num_start列,而它所在的位置False,該值轉到該str_start列。
從一開始df,
condition = df.attr.str.contains(r'^\d')
df['num_start'] = df.attr.where(condition, other=None)
df['str_start'] = df.attr.where(~condition, other=None)
給
Name attr num_start str_start
0 Bob abc123 None abc123
1 Kyle 1230 1230 None
2 Kevin (ab) None (ab)
后記
如果這是一個 xy 問題,您希望根據行是否attr以數字開頭來不同地處理行,請考慮類似
for starts_with_num, group in df.groupby(condition):
# logic
if starts_with_num:
# do the thing (attr starts with a digit)
else:
# do the other thing (attr doesn't start with a digit)
uj5u.com熱心網友回復:
另一種可能的解決方案:
cond = df['attr'].str.replace('[^\w\d]', '').str.contains(r'^\d')
df['num_start'] = np.where(cond, df['attr'], None)
df['str_start'] = np.where(cond, None, df['attr'])
輸出:
Name attr num_start str_start
0 Bob abc123 None abc123
1 Kyle 1230 1230 None
2 Kevin (ab) None (ab)
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/534384.html
