数据框看起来像这样 df::
item_id value
0 101002 1.008665
1 101004 2.025818
2 101005 0.530516
3 101007 0.732918
4 101010 1.787264
... ... ...
621 ZB005 3.464102
622 ZB007 2.345208
623 ZB008 3.464102
624 ZBD002 2.592055
625 ZBD005 2.373321
我想newcol根据列的第一个元素/字母创建一个新列item_id :如果第一个字母item_id是字母表,则返回“alphabet”;如果第一个字母是数字,则返回“number”。
预期输出:
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
我试过:
df['new_component'] = [lambda x: 'alphabet' if x.isalpha() else 'number' for x in df.item_id]
返回的
item_id value new_component
0 101002 1.008665 <function <listcomp>.<lambda> at 0x000002663B04E948>
1 101004 2.025818 <function <listcomp>.<lambda> at 0x000002663B04E828>
2 101005 0.530516 <function <listcomp>.<lambda> at 0x000002663B04EAF8>
3 101007 0.732918 <function <listcomp>.<lambda> at 0x000002663B04EB88>
4 101010 1.787264 <function <listcomp>.<lambda> at 0x000002663B04EC18>
... ... ...
代码有什么问题吗?有更好的方法吗?
慕田峪4524236
ITMISS
相关分类