2 回答

TA貢獻1875條經驗 獲得超5個贊
首先設置默認值的列'alphabet',然后更改帶有數字的列:
df['newcol'] = 'alphabet'
df.loc[df.item_id.str[0].str.isdigit(),'newcol'] = 'number'
如果您更喜歡按照您嘗試過的方式進行操作,請按以下步驟操作:
df['newcol'] = ['number' if x[0].isdigit() else 'alphabet' for x in df.item_id]
或等價:
df['newcol'] = ['alphabet' if x[0].isalpha() else 'number' for x in df.item_id]
輸出:
item_id value newcol
0 101002 1.008665 number
1 101004 2.025818 number
2 101005 0.530516 number
3 101007 0.732918 number
4 101010 1.787264 number
621 ZB005 3.464102 alphabet
622 ZB007 2.345208 alphabet
623 ZB008 3.464102 alphabet
624 ZBD002 2.592055 alphabet
625 ZBD005 2.373321 alphabet

TA貢獻1871條經驗 獲得超8個贊
在列表推導式中,您將創建 lambda 函數列表。
您所需要的只是首先在列表外部定義 lambda 函數
y=lambda x, ...
然后,在列表理解中調用它。
添加回答
舉報