将百分比字符串转换为pandas read_csv中的float

时间:2014-09-04 15:38:21

标签: python pandas

有没有办法转换价值,例如' 34%'在pandas中使用read_csv时直接转到int还是float?我希望它直接读为0.34。

在read_csv中使用它不起作用:

read_csv(..., dtype={'col':np.float})

将csv加载为' df'这也不适用于错误" float()的无效文字:34%"

df['col'] = df['col'].astype(float)

我最终使用了这个有效,但是很长的时间:

df['col'] = df['col'].apply(lambda x: np.nan if x in ['-'] else x[:-1]).astype(float)/100

3 个答案:

答案 0 :(得分:24)

您可以定义自定义函数以将百分比转换为浮点数

In [149]:
# dummy data
temp1 = """index col 
113 34%
122 50%
123 32%
301 12%"""
# custom function taken from https://stackoverflow.com/questions/12432663/what-is-a-clean-way-to-convert-a-string-percent-to-a-float
def p2f(x):
    return float(x.strip('%'))/100
# pass to convertes param as a dict
df = pd.read_csv(io.StringIO(temp1), sep='\s+',index_col=[0], converters={'col':p2f})
df
Out[149]:
        col
index      
113    0.34
122    0.50
123    0.32
301    0.12
In [150]:
# check that dtypes really are floats
df.dtypes
Out[150]:
col    float64
dtype: object

我对浮动代码的百分比是由ashwini的答案提供的:What is a clean way to convert a string percent to a float?

答案 1 :(得分:15)

您与df尝试非常接近。尝试更改:

df['col'] = df['col'].astype(float)

为:

df['col'] = df['col'].str.rstrip('%').astype('float') / 100.0
#                     ^ use str funcs to elim '%'     ^ divide by 100
# could also be:     .str[:-1].astype(...

Pandas支持Python的字符串处理能力。只需在.str之前的字符串函数之前,看看它是否符合您的需要。 (当然,这也包括字符串切片。)

上面我们利用.str.rstrip()去掉尾随的百分号,然后我们将整个数组除以100.0,从百分比转换为实际值。例如,45%相当于0.45。

虽然.str.rstrip('%')也可能只是.str[:-1],但我更愿意明确删除'%',而不是盲目删除最后一个字符,以防万一......

答案 2 :(得分:0)

问:如何从百分比中获取熊猫数据帧/系列?

A

dfp = df[col].str.rstrip('%').astype(float) / 100

说明转换为字符串,如果 % 则去掉最后一个字符。转换为浮点数并除以 100。

@Gary02127 的变体

相关问题