首页 > 解决方案 > 如何从 python 字符串中获取 float 和 int

问题描述

for key in x: 
    if(key=='data'):
        dd = dd.from_dict(x[key])
        dd = dd[:5]

for row in dd.iterrows():
    y = str(row)
    m = re.findall("\d+\.\d+|\d+",y)
    print(m)

我正在尝试使用此代码从字符串中获取一些整数和浮点数。我面临的问题m=re.findall("\d+\.\d+|\d+",y)是没有像我预期的那样工作。

输入数据框是:

0  [2019-10-14T09:15:00+0530, 232.55, 235.2, 231.7, 233, 80683, 0]    
1  [2019-10-14T09:20:00+0530, 233, 233, 231.4, 231.8, 53296, 0]       
2  [2019-10-14T09:25:00+0530, 231.8, 232.8, 231.1, 231.2, 41238, 0]   
3  [2019-10-14T09:30:00+0530, 231.25, 231.4, 230.6, 231.4, 31558, 0]  
4  [2019-10-14T09:35:00+0530, 231.4, 231.75, 230.95, 231.05, 29480, 0]

输出是:

['0', '2019', '10', '14', '09', '15', '00', '0530', '232.55', '235.2', 
'231.7', '233', '80683', '0', '0']
['1', '2019', '10', '14', '09', '20', '00', '0530', '233', '233', '231.4', 
'231.8', '53296', '0', '1']
['2', '2019', '-10', '-14', '09', '25', '00', '0530', '231.8', '232.8', '231.1', '231.2', '41238', '0', '2']

预期输出为:

[ '232.55', '235.2', '231.7', '233', '80683','0']
[ '233', '233', '231.4', '231.8', '53296','0']
[ '231.8', '232.8', '231.1', '231.2', '41238','0']

标签: pythonregexpandas

解决方案


如果日期总是在您的列表中,您可以简单地使用 str 内置 .split() 方法以及列表切片。

在你的情况下,我相信更换

m = re.findall("\d+\.\d+|\d+",y)

经过

m = y.split(',')[1:] #splits 'y' str into list and takes elements from index 1 to end

如果您希望处理的元素始终是第一个元素,则应该可以使用。


推荐阅读