如何用数据框中对象列中的 000 替换“k"或“m"并替换非数字值? [英] How to replace 'k' or 'm' with 000s from object column in dataframe and replace non number values?

查看:55
本文介绍了如何用数据框中对象列中的 000 替换“k"或“m"并替换非数字值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的 df,dtype 是对象不能转换为 int 或 float:

I have a df that looks like this, dtype is object can not cast to int or float:

col1
100
100k
100k-100m
10m
50

如何将 k 替换为 000 并将 m 替换为 000000目的?

How do I replace the k with 000 and the m with 000000 within this column that is type object?

此外,一旦我可以替换 km,我该如何替换所有不是数字的东西?

Furthermore, once I can replace the k or m how do I replace everything that is not a number with nothing?

新的 df 应该是这样的(不是空格):

New df should look like this(not the blank space):

col1
100
100000

10000000
50

试过这个代码:

 df.col1 = (df.col1.replace(r'[KM]+$', '', regex=True).astype(float) * \
          df.col1.str.extract(r'[\d\.]+([KM]+)', expand=False)
             .fillna(1)
             .replace(['K','M'], [10**3, 10**6]).astype(int))

但列必须是浮动的

推荐答案

类似于@user3483203,但使用 str.translate 而不是 str.replace

Similarly to @user3483203, but with str.translate rather than str.replace

df['col1'] = df.col1.str.translate(str.maketrans({'k':'000','m':'000000'}))
>>> df
               col1
0               100
1            100000
2  100000-100000000
3          10000000
4                50

# df['col1'] = pd.to_numeric(df.col1.str.translate(str.maketrans({'k':'000','m':'000000'})),errors='coerce')

#          col1
# 0       100.0
# 1    100000.0
# 2         NaN
# 3  10000000.0
# 4        50.0

这篇关于如何用数据框中对象列中的 000 替换“k"或“m"并替换非数字值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆