仅在一列上设置制表符分隔符

2024-10-06 13:36:44 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个csv文件,当作为数据帧读入时看起来像这样:

          OBJECTID_1           AP_CODE
0         857720               137\t62\t005\tNE
1         857721               137\t62\t004\tNW
2         857724               137\t62\t004\tNE
3         857726               137\t62\t003\tNE
4         857728               137\t62\t003\tNW
5         857729               137\t62\t002\tNW

df.info()返回以下内容:

<class 'pandas.core.frame.DataFrame'>
Int64Index: 9313 entries, 0 to 9312
Data columns (total 2 columns):
OBJECTID_1    9312 non-null float64
AP_CODE       9313 non-null object
dtypes: float64(1), object(1)
memory usage: 181.9+ KB
None

print(repr(open(r'P:\file.csv').read(100)))

返回以下内容:

'OBJECTID_1,AP_CODE\n857720,"137\t62\t005\tNE"\n857721,"137\t62\t004\tNW"\n857724,"137\t62\t004\tNE"\n857726,"137\t'

我想去掉AP_CODE列中的\t,但我不知道为什么它会出现,或者如何删除它.replace不起作用


Tags: columnscsvobjectcodenullapobjectidnon
1条回答
网友
1楼 · 发布于 2024-10-06 13:36:44

如果要使用制表符替换,则需要使用原始字符串,方法是使用r作为字符串文本的前缀:

In [299]: df.AP_CODE.str.replace(r'\\t',' ')
Out[299]:
0    137 62 005 NE
1    137 62 004 NW
2    137 62 004 NE
3    137 62 003 NE
4    137 62 003 NW
5    137 62 002 NW
Name: AP_CODE, dtype: object

相关问题 更多 >