python - 如何从 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']
解决方案
如果日期总是在您的列表中,您可以简单地使用 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
如果您希望处理的元素始终是第一个元素,则应该可以使用。
推荐阅读
- google-analytics - 我可以将(多个数据项)之类的记录发送到谷歌分析并使用这些数据中的任何一个进行分析吗?
- google-maps - 使用离子科尔多瓦谷歌地图的路线回放
- javascript - 如何在 JavaScript 中从数组中分离相同的数据
- c# - 阅读器关闭时调用元数据的尝试无效版本2
- spring - 翻译和理解@Scheduled cron 消息
- unity3d - 在特定情况下忽略碰撞,同时仍将其用作触发器
- postgresql - Postgresql 过程错误 - 记录“旧”没有字段
- python-3.x - Python pip3 install StringIO Not Found for url: https://pypi.org/simple/stringio/
- php - 带有 IN 和多个 where 条件的原始查询?
- graphql - 如何在 GraphQL 的 REST API 中获取具有空格、连字符的字段值