【问题标题】:Python Dataframe: a str has numbers and letters, I want to remove the letters and multiply the remaining numbers by 1,000,000 [duplicate]Python Dataframe:一个str有数字和字母,我想删除字母并将剩余的数字乘以1,000,000 [重复]
【发布时间】:2021-12-08 18:52:43
【问题描述】:

我有一个包含以下值的数据框:

|column a|
---------
|3.5M+   |
|100,000 |
|214,123 |
|1.25M+  |

我想将 3.5M+ 之类的值转换为 3,500,000

我试过了:

regex1 = r'.+M+'
for i in df.a:
    b = re.match(regex1, i)
    if b is not None:
        i = int(np.double(b.string.removesuffix('M+'))*1000000)
    else:
        i = i.replace(',','')

如果我在 out 中添加打印语句,它看起来像是在正确迭代。不幸的是,更改没有保存到数据框中。

【问题讨论】:

  • 你能不能用B+ 表示十亿,或者任何其他缩写?

标签: python regex pandas


【解决方案1】:
>>> import pandas as pd
>>> df = pd.DataFrame({'column_a' : ['3.5M+', '100,000', '214,123', '1.25M+']})
>>> df

    column_a
0   3.5M+
1   100,000
2   214,123
3   1.25M+
>>> df.column_a = df.column_a.str.replace("M\+", '*1000000').str.replace(",", '').apply(eval)
>>> df

    column_a
0   3500000.0
1   100000.0
2   214123.0
3   1250000.0

【讨论】:

    猜你喜欢
    • 2012-11-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-29
    • 1970-01-01
    • 2021-06-05
    • 1970-01-01
    相关资源
    最近更新 更多