python csv filter pairs and nonpairs

Viewed 59

The text file I have is like below:

C1,D1,,,,,,,,
Layer_00 , 3.46ms,Layer_01 , 3.40ms,Layer_02 , 3.56ms,Layer_03 , 3.49ms,Layer_04 , 3.44ms
Layer_05 , 3.45ms,Layer_06 , 3.44ms,Layer_07 , 3.46ms,Layer_08 , 3.45ms,Layer_09 , 3.48ms
C2,D2,,,,,,,,
Layer_00 , 3.42ms,Layer_01 , 3.39ms,Layer_02 , 3.51ms,Layer_03 , 3.41ms,Layer_04 , 3.43ms
Layer_05 , 3.40ms,Layer_06 , 3.43ms,Layer_07 , 3.45ms,Layer_08 , 3.43ms,Layer_09 , 3.42ms

I tried the below:

with open('text.txt', 'r') as file:
    pairs = re.findall('(Layer_\d+)\s,\s(\d+\.\d+)ms', file.read())
pairs = [(k, float(v)) for k,v in pairs]
df = pd.DataFrame(pairs)

and got this:

enter image description here

to get the pairs
however I want to include the C1,D1,C2,D2, the result should be like this:

enter image description here

Does anyone has idea how to solve it?

1 Answers

This should work, but you can't declare the value as float if it will also hold strings ("C1","C2"):

with open('text.txt', 'r') as file:
    pairs = re.findall('(Layer_\d+|C\d)\s*,\s*(\d+\.\d+|D\d)[ms]*', file.read())
pairs = [(k, v) for k,v in pairs]
df = pd.DataFrame(pairs)
Related