猿问

区分数字和字母并在 Python 中创建新列

数据框看起来像这样 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>

... ... ...

代码有什么问题吗?有更好的方法吗?


RISEBY
浏览 106回答 2
2回答

慕田峪4524236

首先设置默认值的列'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]输出:&nbsp; &nbsp; item_id&nbsp; &nbsp; &nbsp;value&nbsp; &nbsp; newcol0&nbsp; &nbsp; 101002&nbsp; 1.008665&nbsp; &nbsp; number1&nbsp; &nbsp; 101004&nbsp; 2.025818&nbsp; &nbsp; number2&nbsp; &nbsp; 101005&nbsp; 0.530516&nbsp; &nbsp; number3&nbsp; &nbsp; 101007&nbsp; 0.732918&nbsp; &nbsp; number4&nbsp; &nbsp; 101010&nbsp; 1.787264&nbsp; &nbsp; number621&nbsp; &nbsp;ZB005&nbsp; 3.464102&nbsp; alphabet622&nbsp; &nbsp;ZB007&nbsp; 2.345208&nbsp; alphabet623&nbsp; &nbsp;ZB008&nbsp; 3.464102&nbsp; alphabet624&nbsp; ZBD002&nbsp; 2.592055&nbsp; alphabet625&nbsp; ZBD005&nbsp; 2.373321&nbsp; alphabet

ITMISS

在列表推导式中,您将创建 lambda 函数列表。您所需要的只是首先在列表外部定义 lambda 函数y=lambda&nbsp;x,&nbsp;...然后,在列表理解中调用它。
随时随地看视频慕课网APP

相关分类

Python
我要回答