在读取文件时,我遇到了一些关于定义多个分隔符的问题。感谢@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
关于python - 列标题中的多个分隔符也会分隔行值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45699077/