我有一个看起来像这样的df,dtype是对象无法转换为int或float:
col1
100
100k
100k-100m
10m
50
如何在此类型为object的列中将k
替换为000
,将m
替换为000000
?
此外,一旦我可以替换k
或m
,我该如何替换所有不是数字的东西?
新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))
但列必须为浮点数
答案 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)