如何用数据帧中对象列中的000替换'k'或'm'并替换非数字值?

时间:2018-10-09 18:53:52

标签: python pandas

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

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

如何在此类型为object的列中将k替换为000,将m替换为000000

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

新df应该如下所示(而不是空白):

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))

但列必须为浮点数

3 个答案:

答案 0 :(得分:2)

类似于@ user3483203,但使用str.translate而不是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

答案 1 :(得分:1)

创建映射字典并使用str.replace

dct = {'k': '000', 'm': '000000'}

df.col1.str.replace(r'|'.join(dct.keys()), lambda x: dct[x.group()])

0                 100
1              100000
2    100000-100000000
3            10000000
4                  50
Name: col1, dtype: object

如果要删除第三行而不是替换,例如在输出中:

(pd.to_numeric(df.col1.str.replace(r'|'.join(dct.keys()),
    lambda x: dct[x.group()]), errors='coerce'))

0         100.0
1      100000.0
2           NaN
3    10000000.0
4          50.0
Name: col1, dtype: float64

答案 2 :(得分:0)

这是我想出的。让我知道你的想法。我做了删除小数位的额外操作。

import pandas as pd

df = pd.Series(['100','100k','100k-100m','10m','50'])

df = df.str.replace('k', '000', regex=True)
df = df.str.replace('m', '000000', regex=True)
df = pd.to_numeric(df, errors='coerce')
df = df.apply(str).str.split('.', expand=True).iloc[ : , 0 ]

print(df)