Skip to main content
 首页 » 编程设计

python之列标题中的多个分隔符也分隔行值

2024年10月01日9jyk

我在读取文件时遇到了关于定义多个分隔符的问题。感谢@piRsquared,它最初在我之前的帖子 reading-files-with-multiple-delimiter-in-column-headers-and-skipping-some-rows 中解决了

当我详细查看我的真实数据时,我 意识到某些列具有 .cd 或 .dvd 扩展名,当我应用上面的解决方案时,它们也被分离为一个新列,并且上面的解决方案开始不起作用!

b.txt

skip1 
 A1| A2 |A3 |A4# A5# A6 A7| A8 , A9 
1,2,3,4,5.cd,6,7,8.dvd,9 
1,2,3,4,5.cd,6,7,8.dvd,9 
1,2,3,4,5.cd,6,7,8.dvd,9 
 
END123 
Some other data starts from here 

并使用上面的 solution 读取这个 b.txt 文件

txt = open('b.txt').read().split('\nEND')[0] 
pd.read_csv( 
    pd.io.common.StringIO(txt), 
    sep=r'\W+', 
    skiprows=1,index_col=False, engine='python') 
 
   A1  A2  A3  A4  A5  A6  A7  A8  A9 
0   1   2   3   4   5  cd   6   7   8 
1   1   2   3   4   5  cd   6   7   8 
2   1   2   3   4   5  cd   6   7   8 

A5列应该有行数

5.cd 
5.cd 
5.cd 

A9列也一样

8.dvd 
8.dvd 
8.dvd 

我们应该有 A9 列,但似乎由于这个冲突它消失了。

编辑:

我把几乎相似的身份放到我的真实数据中

 skip rows 
 A1| A2| A3|A4# A5#  |  A6 | A7  , A8,  A9  | A10 | 
 1 | 2 | 3 |4 # 5 #  | 6.cd|7.dvd,   ,      | 10  |  
 1 | 2 | 3 |4 # 5 #  | 6.cd|     ,   ,   9  | 10  | 
 1 | 2 | 3 |4 # 5 #  |     |7.dvd,   ,      | 10  | 
 
END123 
Some other data starts from here 

尝试过

txt = open('real_dat.txt').read().split('\nEND')[0] 
_, h, txt = txt.split('\n', 2) 
pat = r'[\|, ,#,\,]+' 
names = re.split(pat, h.strip()) 
 
df=pd.read_csv( 
    pd.io.common.StringIO(txt), 
    names=names,skiprows=1,index_col=False, 
    engine='python') 

得到了这个输出!

请您参考如下方法:

更新的答案
摆脱空格更容易...让我知道这是否有效

txt = open('b.txt').read().split('\nEND')[0] \ 
    .replace(' ', '').replace('|\n', '\n').split('\n', 1)[1] 
 
pd.read_csv( 
    pd.io.common.StringIO(txt), 
    sep=r'#\||\||#|,', 
    engine='python') 
 
   A1  A2  A3  A4  A5    A6     A7  A8   A9  A10 
0   1   2   3   4   5  6.cd  7.dvd NaN  NaN   10 
1   1   2   3   4   5  6.cd    NaN NaN  9.0   10 
2   1   2   3   4   5   NaN  7.dvd NaN  NaN   10 

旧答案

我使用 \W+ 作为一种快速简便的方法来解析您显示的内容。下面我使用了一些更具体的内容来满足您实际需要的分隔符。

txt = open('b.txt').read().split('\nEND')[0] 
pd.read_csv( 
    pd.io.common.StringIO(txt), 
    sep=r'[\|, ,#,\,]+', 
    skiprows=1,index_col=False, engine='python') 
 
   A1  A2  A3  A4    A5  A6  A7     A8  A9 
0   1   2   3   4  5.cd   6   7  8.dvd   9 
1   1   2   3   4  5.cd   6   7  8.dvd   9 
2   1   2   3   4  5.cd   6   7  8.dvd   9 

但是,我仍然认为这是一种更简洁的方法。在这里,我将 header 的解析与其余数据的解析分开。这样,我假设数据应该只使用 , 作为分隔符。

txt = open('b.txt').read().split('END')[0] 
_, h, txt = txt.split('\n', 2) 
pat = r'[\|, ,#,\,]+' 
names = re.split(pat, h.strip()) 
 
pd.read_csv( 
    pd.io.common.StringIO(txt), 
    names=names, header=None, 
    engine='python') 
 
   A1  A2  A3  A4    A5  A6  A7     A8  A9 
0   1   2   3   4  5.cd   6   7  8.dvd   9 
1   1   2   3   4  5.cd   6   7  8.dvd   9 
2   1   2   3   4  5.cd   6   7  8.dvd   9