为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

RISEBY 2023-09-26 16:28:03
数据框看起来像这样 df::    item_id value 0   101002  1.0086651   101004  2.0258182   101005  0.5305163   101007  0.7329184   101010  1.787264... ... ...621 ZB005   3.464102622 ZB007   2.345208623 ZB008   3.464102624 ZBD002  2.592055625 ZBD005  2.373321我想newcol根据列的第一个元素/字母创建一个新列item_id :如果第一个字母item_id是字母表,则返回“alphabet”;如果第一个字母是数字,则返回“number”。预期输出:    item_id value     newcol0   101002  1.008665  number1   101004  2.025818  number 2   101005  0.530516  number3   101007  0.732918  number4   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_component0   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>... ... ...代码有什么问题吗?有更好的方法吗?
查看完整描述

2 回答

?
慕田峪4524236

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


查看完整回答
反对 回复 2023-09-26
?
ITMISS

TA贡献1871条经验 获得超8个赞

在列表推导式中,您将创建 lambda 函数列表。

您所需要的只是首先在列表外部定义 lambda 函数

y=lambda x, ...

然后,在列表理解中调用它。


查看完整回答
反对 回复 2023-09-26
  • 2 回答
  • 0 关注
  • 105 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信