Pandas:将包含类似于“10%”和“0.10”的字符串的系列转换为数字。

7
如何将包含字符串 "10%" 和 "0.10" 类型的 Pandas series 转换为数值类型?
如果 series 只包含 "0.10" 类型的字符串,可以使用 pd.to_numeric。
如果 series 包含 "10%" 类型的字符串,可以使用 str.replace("%","") 去掉百分号,并使用 pd.to_numeric 然后除以 100。
问题是如何处理同时包含 "0.10" 和 "10%" 类型字符串的 series。如何最好地将其转换为正确的数值类型系列?
可以先创建一个临时系列,根据字符串中是否有 "%" 分别赋值为 True 或 False,然后根据此应用函数进行转换。但这似乎效率不高。是否有更好的方法?
参考尝试:
mixed = pd.Series(["10%","0.10","5.5%","0.02563"])
mixed.str.replace("%","").astype("float")/100

0    0.100000
1    0.001000
2    0.055000
3    0.000256
dtype: float64
# This doesn't work, because even the 0.10 and 0.02563 are divided by 100.
6个回答

8

你需要一个条件。以下是一种可能的方式:

l = pd.Series((float(x.strip('%'))/100 if '%' in x else float(x) for x in mixed))
print(l)

0    0.10000
1    0.10000
2    0.05500
3    0.02563
dtype: float64

8
一个基于这个回答的非常简洁的解决方案是:
from pandas import Series, to_numeric

mixed = Series(["10%", "0.10", "5.5%", "0.02563"])

print(to_numeric(mixed.str.replace("%", "e-2")))
# 0    0.10000
# 1    0.10000
# 2    0.05500
# 3    0.02563
# dtype: float64

5
mixed = mixed.apply(lambda x: float(x[:-1])/100 if '%' in x else float(x))

输出:

0    0.10000
1    0.10000
2    0.05500
3    0.02563
dtype: float64

5
最简单的解决方案是使用掩码选择条目,并批量处理它们:
from pandas import Series, to_numeric

mixed = Series(["10%", "0.10", "5.5%", "0.02563"])

# make an empty series with similar shape and dtype float
converted = Series(index=mixed.index, dtype='float')

# use a mask to select specific entries
mask = mixed.str.contains("%")

converted.loc[mask] = to_numeric(mixed.loc[mask].str.replace("%", "")) / 100
converted.loc[~mask] = to_numeric(mixed.loc[~mask])

print(converted)
# 0    0.10000
# 1    0.10000
# 2    0.05500
# 3    0.02563
# dtype: float64

3

尝试:

mixed = pd.Series(["10%", "0.10", "5.5%", "0.02563"])


mixed = mixed.str.replace("%", "e-02")
print(pd.to_numeric(mixed))

打印:

0    0.10000
1    0.10000
2    0.05500
3    0.02563
dtype: float64

1
你可以使用其中任何一个
尝试 "apply"
mixed = pd.Series(["10%","0.10","5.5%","0.02563"])

def percent_to_float(x):
    if x.endswith("%"):
        x = x.rstrip("%")
        return float(x)/100
    else:
        return float(x)

cleaned = mixed.apply(lambda x : percent_to_float(x)) 

print(cleaned)

还有 str.replace

mixed = pd.Series(["10%", "0.10", "5.5%", "0.02563"])
mixed = mixed.str.replace("%", "e-02")

print(pd.to_numeric(mixed))

您还可以使用 正则表达式替换 以及 apply

import re

mixed = pd.Series(["10%","0.10","5.5%","0.02563"])

def percent_to_float(x):
    return float(re.sub( "%", "e-02", x))

cleaned = mixed.apply(lambda x : percent_to_float(x)) 

print(cleaned)

无论使用何种方法,您都将获得

0    0.10000
1    0.10000
2    0.05500
3    0.02563
dtype: float64

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接