在pandas中使用read_csv时,有没有办法将'34%'等值直接转换为int或float?我希望它直接读为0.34.
在read_csv中使用它不起作用:
read_csv(..., dtype={'col':np.float})
Run Code Online (Sandbox Code Playgroud)
将csv加载为'df'后,这也无法使用错误"float()的无效文字:34%"
df['col'] = df['col'].astype(float)
Run Code Online (Sandbox Code Playgroud)
我最终使用了这个有效,但是很长时间:
df['col'] = df['col'].apply(lambda x: np.nan if x in ['-'] else x[:-1]).astype(float)/100
Run Code Online (Sandbox Code Playgroud)
EdC*_*ica 28
您可以定义自定义函数以将百分比转换为浮点数
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
Run Code Online (Sandbox Code Playgroud)
我对浮动代码的百分比是由ashwini的答案提供的:什么是将字符串百分比转换为浮点数的简洁方法?
Gar*_*127 20
你的df尝试非常接近.尝试改变:
df['col'] = df['col'].astype(float)
Run Code Online (Sandbox Code Playgroud)
至:
df['col'] = df['col'].str.rstrip('%').astype('float') / 100.0
# ^ use str funcs to elim '%' ^ divide by 100
# could also be: .str[:-1].astype(...
Run Code Online (Sandbox Code Playgroud)
Pandas支持Python的字符串处理能力.只需在您想要的字符串函数之前.str,看看它是否符合您的需要.(当然,这也包括字符串切片.)
上面我们利用.str.rstrip()去掉尾随的百分号,然后我们将数组全部除以100.0,从百分比转换为实际值.例如,45%相当于0.45.
虽然.str.rstrip('%')也可以.str[:-1],但我更喜欢明确删除'%'而不是盲目删除最后一个字符,以防万一...
| 归档时间: |
|
| 查看次数: |
28403 次 |
| 最近记录: |