【问题标题】:How to split key, value from text file using pandas?如何使用熊猫从文本文件中拆分键、值?
【发布时间】:2016-07-14 10:12:48
【问题描述】:

我有这样的输入文本文件:

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

我想拆分这个键值对并以如下格式显示:

Output.txt-

index[0]
1     88
2     1438
3     kkk
4     7.7
5     00
6     
7     66
8     a
9    

index[1]
1     13
2     1438
3     DDD
4     157.73
5    
6     00
7     08
8     b
9     k

请参阅在索引[0] 中,第 6 和第 9 条记录的值为空白,因为 6 在另一列中可用,但在此列中不可用。像这样在 index[1] 中的第 5 条记录是空白的。

程序代码-

df = pd.read_csv(inputfile, index_col=None, names=['text'])

    #spliting two times with respect to (= & |) and saving into stack
    s = df.text.str.split('|', expand=True).stack().str.split('=', expand=True)

    #giving index's as empty string ('') i.e. for removing
    s.columns = ['idx','']

    #rename_axis(None) for excluding index values  
    dfs = [g.set_index('idx').rename_axis(None) for i, g in s.groupby(level=0)]

    #length for iterating through list
    dfs_length = len(dfs)


    #opening output file
    with open(outputfile + 'output.txt','w') as file_obj:
        i = 0
        while i < dfs_length:
            #index of each column
            s = '\nindex[%d]\n'%i
            #writing index to file
            file_obj.write(str(s))
            #print '\nindex[%d]'%i
            #print dfs[i]
            #wriring actual contents to file
            file_obj.write(str(dfs[i])+'\n')
            i = i + 1

我得到了这个输出:

output.txt-

index[0]
1     88
2     1438
3     kkk
4     7.7
5     00
7     66
8     a

index[1]
1     13
2     1438
3     DDD
4     157.73
6     00
7     08
8     b
9     k

我只得到输入文本文件中可用的记录。如何将记录值保留为空白?

【问题讨论】:

  • 看起来像家庭作业。
  • @ErnestTen,不,它没有。 IMO,这是一个有趣的问题......
  • @kitty,你有固定数量的属性吗(1=...,...,9=...)?
  • @MaxU- 不。这不是固定的。我必须保留空白或 NaN 他们的。

标签: python pandas dataframe key key-value


【解决方案1】:

您可以将.str.extract() 函数与生成的正则表达式结合使用:

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)

测试:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-19
    相关资源
    最近更新 更多