Hien Le
Hien Le

Reputation: 47

How do I transform this list into a dataframe

I have this list that represent Fedex tracking

history = ['Tuesday, March 16, 2021', '3:03 PM Hollywood, FL\nDelivered\nLeft at front door. Signature Service not requested.', '5:52 AM MIAMI, FL\nOn FedEx vehicle for delivery', '5:40 AM MIAMI, FL\nAt local FedEx facility', 'Monday, March 15, 2021', '11:42 PM OCALA, FL\nDeparted FedEx location', '10:01 PM OCALA, FL\nArrived at FedEx location', '8:28 PM OCALA, FL\nIn transit', '12:42 AM OCALA, FL\nIn transit']

How do I transform this list into this 3 columns dataframe enter image description here

Upvotes: 1

Views: 90

Answers (2)

fthomson
fthomson

Reputation: 789

ok this is a bit hacky but might get the job done if the format is consistent, long term regex might be a better approach

col1 = []
col2 = []
col3 = []
for h in history:
    if 'FL' in h:
        col1.append(date)
        new_list = h.split(',')
        item2 = new_list[0][4:]
        item3 = new_list[1][4:]
        col2.append(item2.replace('\n', '. '))
        col3.append(item3.replace('\n', '. '))
    else:
        date = h

pd.DataFrame({'col1': col1,
              'col2': col2,
              'col3': col3})

Upvotes: 0

Andrej Kesely
Andrej Kesely

Reputation: 195593

history = [
    "Tuesday, March 16, 2021",
    "3:03 PM Hollywood, FL\nDelivered\nLeft at front door. Signature Service not requested.",
    "5:52 AM MIAMI, FL\nOn FedEx vehicle for delivery",
    "5:40 AM MIAMI, FL\nAt local FedEx facility",
    "Monday, March 15, 2021",
    "11:42 PM OCALA, FL\nDeparted FedEx location",
    "10:01 PM OCALA, FL\nArrived at FedEx location",
    "8:28 PM OCALA, FL\nIn transit",
    "12:42 AM OCALA, FL\nIn transit",
]


import re

r = re.compile("^(?:Sunday|Monday|Tuesday|Wednesday|Thursday|Friday|Saturday)")

data, cur_group = [], ""
for line in history:
    if r.match(line):
        cur_group = line
    else:
        data.append([cur_group, *line.split("\n", maxsplit=1)])

df = pd.DataFrame(data)
print(df)

Prints:

                         0                      1                                                  2
0  Tuesday, March 16, 2021  3:03 PM Hollywood, FL  Delivered\nLeft at front door. Signature Servi...
1  Tuesday, March 16, 2021      5:52 AM MIAMI, FL                      On FedEx vehicle for delivery
2  Tuesday, March 16, 2021      5:40 AM MIAMI, FL                            At local FedEx facility
3   Monday, March 15, 2021     11:42 PM OCALA, FL                            Departed FedEx location
4   Monday, March 15, 2021     10:01 PM OCALA, FL                          Arrived at FedEx location
5   Monday, March 15, 2021      8:28 PM OCALA, FL                                         In transit
6   Monday, March 15, 2021     12:42 AM OCALA, FL                                         In transit

Upvotes: 2

Related Questions