首页 > 解决方案 > 如果单元格开头有 -* 结尾有 *,则更改单元格中的值

问题描述

我有一个看起来像这样的数据框

Name     salary    age    Id
Steve    23000    -*29*   22
Mark    -*2900*    24     82
John     40000     26   -*72*

我想

Name     salary    age    Id
Steve    23000     29     22
Mark     2900      24     82
John     40000     26     72

我努力了。

df.apply(lambda x:x[2:-1] if x.str.startwith('="') and x.str.endwith('"') else x)

我收到错误

ValueError: The truth of a series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()

我想我没有到达单元格,而是将更改应用于列。

标签: pythondataframenumpy

解决方案


IIUC,您要删除-*字符:

df = df.apply(lambda c: c.str.strip('-*'))

输出:

    Name salary age  Id
0  Steve  23000  29  22
1   Mark   2900  24  82
2   John  40000  26  72

注意。您的单元格仍将是字符串,以转换为数字:

df = df.apply(lambda c: pd.to_numeric(c.str.strip('-*'), errors='ignore'))

推荐阅读