string Python:将字符串(以科学计数法)转换为浮点数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/23636509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python: Convert string (in scientific notation) to float
提问by Dr. Toboggan
I'm trying to import a large .csv file containing text and numbers using genfromtxt in numpy. I'm only interested in two columns. I have most of the import sorted out with:
我正在尝试在 numpy 中使用 genfromtxt 导入一个包含文本和数字的大型 .csv 文件。我只对两列感兴趣。我已经整理了大部分导入:
def importfile(root):
data = root.entry.get()
atw = np.genfromtxt(data, delimiter=",",
skip_header=1,
skip_footer=2,
autostrip=True,
usecols=(25,26),
dtype=("|S10"))
elem = atw[:,0]
concs = atw[:,1]
print(elem)
print(concs)
With output for elem and concs respectively:
分别为 elem 和 concs 输出:
['Na2O' 'MgO' 'Al2O3' 'SiO2' 'P2O5' 'SO3' 'Cl' 'K2O' 'CaO' 'TiO2' 'Cr2O3'
'MnO' 'FeO' 'NiO' 'Cu2O' 'ZnO' 'Ga2O3' 'SrO' 'Y2O3']
['3.76E+00' '1.31E+01' '1.14E+01' '4.04E+01' '1.24E+00' '5.89E-02'
'2.43E-02' '1.53E+00' '1.49E+01' '2.87E+00' '6.05E-02' '1.96E-01'
'1.17E+01' '3.69E-02' '8.73E-03' '1.39E-02' '1.93E-03' '1.88E-01'
'5.58E-03']
I have tried many different things for converting the concs string into a float, but it doesn't seem to like the fact that the concs are in scientific notation.... does there exist a way to turn the concs values into a float? Thanks in advance for your support.
我已经尝试了许多不同的方法将 concs 字符串转换为浮点数,但它似乎不喜欢 concs 采用科学记数法这一事实......是否存在将 concs 值转换为浮点数的方法?预先感谢您的支持。
回答by RichieHindle
The float
function can do this:
该float
函数可以这样做:
>>> float('1.31E+01')
13.1
or for a list:
或列表:
>>> map(float, ['3.76E+00', '1.31E+01', '1.14E+01'])
[3.76, 13.1, 11.4]
回答by mist42nz
with open( datafile,'r' ) as inData:
for line in inData:
j = list( map( float, filter( None , [ x for x in line.strip().split(',') ] )) )
Just mentioned generally, as it solves a similar problem that brought me to this page.
只是一般性地提到,因为它解决了使我进入此页面的类似问题。
回答by Yury Wallet
MAybe that will be helpful for anybody, I had similar problem and I've found on stackoverflow about applying pandas to_numeric to DataFrame columns including replacing commas with dots
也许这对任何人都有帮助,我有类似的问题,我在 stackoverflow 上发现了关于将 Pandas to_numeric 应用于 DataFrame 列,包括用点替换逗号
import re
import pandas as pd
atw[cc] = pd.to_numeric(atw[cc].apply(lambda x: re.sub(',', '.', str(x))))