Skip to main content
 首页 » 编程设计

python之如何用 TSV 文件中的制表符替换逗号

2024年10月24日13lidabo

在我下面的数据框中,我试图用制表符和它下面的字符串替换 curv_typ,maturity,bonds,geo\time 列中的逗号,这样我就可以创建新的来自此的专栏。

 curv_typ,maturity,bonds,geo\time  2015M06D16   2015M06D15   2015M06D11   \ 
0                 PYC_RT,Y1,GBAAA,EA        -0.24        -0.24        -0.24    
1               PYC_RT,Y1,GBA_AAA,EA        -0.02        -0.03        -0.10    
2                PYC_RT,Y10,GBAAA,EA         0.94         0.92         0.99    
3              PYC_RT,Y10,GBA_AAA,EA         1.67         1.70         1.60    
4                PYC_RT,Y11,GBAAA,EA         1.03         1.01         1.09  

代码如下,但它没有去掉逗号,这就是我挣扎的地方。

import os 
import urllib2 
import gzip 
import StringIO 
import pandas as pd 
 
baseURL = "http://ec.europa.eu/eurostat/estat-navtree-portlet-prod/BulkDownloadListing?file=" 
filename = "data/irt_euryld_d.tsv.gz" 
outFilePath = filename.split('/')[1][:-3] 
 
response = urllib2.urlopen(baseURL + filename) 
compressedFile = StringIO.StringIO() 
compressedFile.write(response.read()) 
 
compressedFile.seek(0) 
 
decompressedFile = gzip.GzipFile(fileobj=compressedFile, mode='rb')  
 
with open(outFilePath, 'w') as outfile: 
    outfile.write(decompressedFile.read()) 
 
#Now have to deal with tsv file 
import csv 
 
outFilePath = filename.split('/')[1][:-3] #As in the code above, just put here for reference 
csvout = 'C:\Users\Sidney\ECB.tsv' 
outfile = open(csvout, "w") 
with open(outFilePath, "rb") as f: 
    for line in f.read(): 
        line.replace(",", "\t") 
        outfile.write(line) 
outfile.close() 
 
df = pd.DataFrame.from_csv("ECB.tsv", sep="\t", index_col=False) 

谢谢

请您参考如下方法:

拆分列名以生成新的列名,然后调用向量化的 str split参数 expand=True 的方法:

In [26]: 
cols = 'curv_typ,maturity,bonds,geo\\time'.split(',') 
df[cols] = df['curv_typ,maturity,bonds,geo\\time'].str.split(',', expand=True) 
df 
 
Out[26]: 
  curv_typ,maturity,bonds,geo\time  2015M06D16  2015M06D15  2015M06D11  \ 
0               PYC_RT,Y1,GBAAA,EA       -0.24       -0.24       -0.24    
1             PYC_RT,Y1,GBA_AAA,EA       -0.02       -0.03       -0.10    
2              PYC_RT,Y10,GBAAA,EA        0.94        0.92        0.99    
3            PYC_RT,Y10,GBA_AAA,EA        1.67        1.70        1.60    
4              PYC_RT,Y11,GBAAA,EA        1.03        1.01        1.09    
 
  curv_typ maturity    bonds geo\time   
0   PYC_RT       Y1    GBAAA       EA   
1   PYC_RT       Y1  GBA_AAA       EA   
2   PYC_RT      Y10    GBAAA       EA   
3   PYC_RT      Y10  GBA_AAA       EA   
4   PYC_RT      Y11    GBAAA       EA   

编辑

对于 0.16.0 及更早的 pandas 版本,您需要使用以下行:

df[cols] = df['curv_typ,maturity,bonds,geo\\time'].str.split(',').apply(pd.Series)