kit kit - 4 months ago 47
Python Question

How to read text file's key, value pair using pandas?

I want to parse one text file which contains following data.

Input.txt-

1=88|11=1438|15=KKK|45=7.7|45=00|21=66|86=a
4=13|4=1388|49=DDD|8=157.73|67=00|45=08|84=b|45=k
6=84|41=18|56=TTT|67=1.2|4=21|45=78|07=d


In this input text file no columns are fixed it may be 10 or 20 or anything. I want to parse this file using pandas. Output should contain :

output.txt-

index[0]
1 88
11 1438
15 kkk
45 7.7
45 00
21 66
86 a

index[1]
4 13
4 1388
49 DDD
8 157.73
67 00
45 08
84 b
45 k


Any suggestions about how I can get this type of result?

Answer

You can first read_csv with separator which is not in data e.g. ;, then double split with stack:

import pandas as pd
import numpy as np
import io

temp=u"""1=88|11=1438|15=KKK|45=7.7|45=00|21=66|86=a
4=13|4=1388|49=DDD|8=157.73|67=00|45=08|84=b|45=k
6=84|41=18|56=TTT|67=1.2|4=21|45=78|07=d
"""
#after testing replace io.StringIO(temp) to filename
df = pd.read_csv(io.StringIO(temp), sep=";", index_col=None, names=['text'])

print (df)
                                                text
0        1=88|11=1438|15=KKK|45=7.7|45=00|21=66|86=a
1  4=13|4=1388|49=DDD|8=157.73|67=00|45=08|84=b|45=k
2           6=84|41=18|56=TTT|67=1.2|4=21|45=78|07=d
s = df.text.str.split('|', expand=True).stack().str.split('=', expand=True)
print (s)
      0       1
0 0   1      88
  1  11    1438
  2  15     KKK
  3  45     7.7
  4  45      00
  5  21      66
  6  86       a
1 0   4      13
  1   4    1388
  2  49     DDD
  3   8  157.73
  4  67      00
  5  45      08
  6  84       b
  7  45       k
2 0   6      84
  1  41      18
  2  56     TTT
  3  67     1.2
  4   4      21
  5  45      78
  6  07       d
dfs = [g.set_index(0).rename_axis(None) for i, g in s.groupby(level=0)]
print (dfs[0])
       1
1     88
11  1438
15   KKK
45   7.7
45    00
21    66
86     a
for i, g in s.groupby(level=0):
    print (g.set_index(0).rename_axis(None))
       1
1     88
11  1438
15   KKK
45   7.7
45    00
21    66
86     a
         1
4       13
4     1388
49     DDD
8   157.73
67      00
45      08
84       b
45       k
      1
6    84
41   18
56  TTT
67  1.2
4    21
45   78
07    d
Comments