在 pandas 数据框中操纵时间范围 [英] Manipulate time-range in a pandas Dataframe
问题描述
需要清理csv导入,这给了我一段时间(以字符串形式)。代码在底部;我目前在df上使用正则表达式和 replace()
来转换其他字符。只是不确定如何:
Need to clean up a csv import, which gives me a range of times (in string form). Code is at bottom; I currently use regular expressions and replace()
on the df to convert other chars. Just not sure how to:
- 选择当前的24小时格式编号并添加:00
- 如何选择12小时格式数字并使它们成为24小时格式。
输入(从csv导入):
Input (from csv import):
break_notes
0 15-18
1 18.30-19.00
2 4PM-5PM
3 3-4
4 4-4.10PM
5 15 - 17
6 11 - 13
到目前为止,我看起来像(删除空格,AM / PM,用冒号替换点):
So far I have got it to look like (remove spaces, AM/PM, replace dot with colon):
break_notes
0 15-18
1 18:30-19:00
2 4-5
3 3-4
4 4-4:10
5 15-17
6 11-13
但是,我希望它看起来像这样('HH:MM-HH:MM'格式):
However, I would like it to look like this ('HH:MM-HH:MM' format):
break_notes
0 15:00-18:00
1 18:30-19:00
2 16:00-17:00
3 15:00-16:00
4 16:00-16:10
5 15:00-17:00
6 11:00-13:00
我的代码是:
data = pd.read_csv('test.csv')
data.break_notes = data.break_notes.str.replace(r'([P].|[ ])', '').str.strip()
data.break_notes = data.break_notes.str.replace(r'([.])', ':').str.strip()
推荐答案
根据请求的输入数据所需的转换器功能。 convert_entry
进行完整的值输入,将其拆分为一个破折号,然后将其结果传递给 convert_single
,因为两者的一半条目可以单独转换。每次转换后,它将它们与破折号合并。
Here is the converter function that you need based on your requested input data. convert_entry
takes complete value entry, splits it on a dash, and passes its result to convert_single
, since both halfs of one entry can be converted individually. After each conversion, it merges them with a dash.
convert_single
使用正则表达式搜索时间中的重要部分串。
它以一些数字 \d +
(代表小时)开头,然后可选地是一个点或冒号以及一些其他的数字 [ 。:]?(\d +)?
(代表分钟)。然后是可选的AM还是PM (AM | PM)?
(在这种情况下,仅PM是相关的)
convert_single
uses regex to search for important parts in the time string.
It starts with a some numbers \d+
(representing the hours), then optionally a dot or a colon and some more number [.:]?(\d+)?
(representing the minutes). And after that optionally AM or PM (AM|PM)?
(only PM is relevant in this case)
import re
def convert_single(s):
m = re.search(pattern="(\d+)[.:]?(\d+)?(AM|PM)?", string=s)
hours = m.group(1)
minutes = m.group(2) or "00"
if m.group(3) == "PM":
hours = str(int(hours) + 12)
return hours.zfill(2) + ":" + minutes.zfill(2)
def convert_entry(value):
start, end = value.split("-")
start = convert_single(start)
end = convert_single(end)
return "-".join((start, end))
values = ["15-18", "18.30-19.00", "4PM-5PM", "3-4", "4-4.10PM", "15 - 17", "11 - 13"]
for value in values:
cvalue = convert_entry(value)
print(cvalue)
这篇关于在 pandas 数据框中操纵时间范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!