亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

txt 文件中有兩種不同類型的數據,我如何使用 pandas 來交互每一行并添加相應的數據

txt 文件中有兩種不同類型的數據,我如何使用 pandas 來交互每一行并添加相應的數據

慕的地6264312 2023-09-26 14:57:28
我最近獲取了當地健身房的數據,我正在嘗試對數據進行標準化,以便可以創建一個“健身房注冊”對象,其中包含注冊該會話的所有人員。文本文件如下所示:Sep 30th? '20 at 9:00AM Until Sep 30th? '20 at 10:00AMJD? John Doe? ??AW? Alice Wonderland? ??IM? Iron ManSep 30th? '20 at 8:00AM Until Sep 30th? '20 at 9:00AMJD? John Doe? ??AW? Alice Wonderland? ??IM? Iron Man我已經能夠使用 pandas 按列 [姓名首字母,姓名] 分隔注冊,但我不知道如何檢測何時一行對應于時間段而不是注冊的人。因此,程序運行后,每一行都應包含 [姓名首字母、姓名、時間段] 列對我來說處理這些數據最簡單的方法就是采用這種格式,JD? John Doe? ? Sep 30th? '20 at 9:00AM Until Sep 30th? '20 at 10:00AMAW? Alice Wonderland? ? Sep 30th? '20 at 9:00AM Until Sep 30th? '20 at 10:00AMIM? Iron Man? ? Sep 30th? '20 at 9:00AM Until Sep 30th? '20 at 10:00AMJD? John Doe? ? Sep 30th? '20 at 8:00AM Until Sep 30th? '20 at 9:00AMAW? Alice Wonderland? ? Sep 30th? '20 at 8:00AM Until Sep 30th? '20 at 9:00AMIM? Iron Man? ? ? Sep 30th? '20 at 8:00AM Until Sep 30th? '20 at 9:00AM我嘗試遍歷每一行,一旦出現一個時隙行,我就會將該行附加到下一行,直到出現新的時隙。def testSort():? ? with open("1-weak-gym.txt") as fp:? ? ? ? id= []? ? ? ? totalSheet=[]? ? ? ? timeSlot = []? ? ? ? lastLine=[]? ? ? ? for ln in fp:? ? ? ? ? ? if ln.startswith("Sep"): ##this is a time slot? ? ? ? ? ? ? ? timeSlot.clear()? ? ? ? ? ? ? ? timeSlot.append(ln[0:]) ##save that time slot as the lastDate variable? ? ? ? ? ? else:? ? ? ? ? ? ? ? if (timeSlot):? ? ? ? ? ? ? ? ? ? totalSheet.append(timeSlot) ##append the time slot? ? ? ? ? ? ? ? ? ? totalSheet.append(ln[0:]) ##append the name line? ? ? ? ? ? ? ? else:? ? ? ? ? ? ? ? ? ? print('Hello eror')? ? print(totalSheet, file=open("newOuput.txt","a"))?
查看完整描述

1 回答

?
慕少森

TA貢獻2019條經驗 獲得超9個贊

您可以嘗試這種方法(如果標題行末尾的時間有很強的模式):


import re


def is_time_format(s):

    time_re = re.compile(r'\b((1[0-2]|0?[1-9]):([0-5][0-9])([AaPp][Mm]))')

    return bool(time_re.match(s))


with open("1-weak-gym.txt") as fp:

    new_lines = []

    extra_info = ''

    for line in fp:

        last_bit = line.split(' ')[-1]

        if is_time_format(last_bit):

            extra_info = line

            continue

        else:

            new_lines.append(line.rstrip() + '\t' + extra_info)


open("newOutput", 'w').writelines(new_lines)

然后您將獲得正確格式的文件。


查看完整回答
反對 回復 2023-09-26
  • 1 回答
  • 0 關注
  • 83 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號