Skip to content Skip to sidebar Skip to footer

How To Split Key, Value From Text File Using Pandas?

I'm having input text file like this : Input.txt- 1=88|2=1438|3=KKK|4=7.7|5=00|7=66|8=a 1=13|2=1388|3=DDD|4=157.73|6=00|7=08|8=b|9=k I want to split this key and value pairs and s

Solution 1:

you can do it using .str.extract() function in conjunction with a generated RegEx:

pat = r'(?:1=)?(?P<a1>[^\|]*)?'

# you may want to adjust the right bound of the range interval
for i in range(2, 12):
    pat += r'(?:\|{0}=)?(?P<a{0}>[^\|]*)?'.format(i)

new = df.val.str.extract(pat, expand=True)

Test:

In [178]: df
Out[178]:
                                            val
0         1=88|2=1438|3=KKK|4=7.7|5=00|7=66|8=a
1  1=13|2=1388|3=DDD|4=157.73|6=00|7=08|8=b|9=k
2                                1=11|3=33|5=55

In [179]: new
Out[179]:
   a1    a2   a3      a4  a5  a6  a7 a8 a9 a10 a11
0  88  1438  KKK     7.7  00      66  a
1  13  1388  DDD  157.73      00  08  b  k
2  11         33          55

Post a Comment for "How To Split Key, Value From Text File Using Pandas?"