Python:使用pandas打开txt时保持前导零

时间:2017-12-05 17:51:38

标签: python pandas dataframe text-files leading-zero

我有这个txt文件:

Tu 11:44:00 119 52913161 DETECTOR STATE 0001
Tu 11:44:00 119 52913161 DETECTOR STATE 1100
Tu 11:44:02 119 52913161 DETECTOR STATE 0000
Tu 11:44:02 119 52913161 DETECTOR STATE 1110
Tu 11:44:04 119 52913161 DETECTOR STATE 0000
Tu 11:44:04 119 52913161 DETECTOR STATE 0011

我使用此代码在Python(Jupyter Notebook)中打开:

import pandas as pd
data= pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None)
data.columns = ["day", "time", "street", "sensor", "type", "state", "bits"]

我得到了这个输出:

    day time    street  sensor  type    state   bits
0   Tu  11:44:00    119 52913161    DETECTOR    STATE      1
1   Tu  11:44:00    119 52913161    DETECTOR    STATE   1100
2   Tu  11:44:02    119 52913161    DETECTOR    STATE      0
3   Tu  11:44:02    119 52913161    DETECTOR    STATE   1110
4   Tu  11:44:04    119 52913161    DETECTOR    STATE      0
5   Tu  11:44:04    119 52913161    DETECTOR    STATE     11

如何保持领先零?

我尝试过以下选项:

 data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None, dtype={'column': object}) 


 data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None).astype(str)


 data = pd.read_csv('EXPORT20171205114501_1.txt', sep=" ", header=None, converters={'ColName': str})

以上选项均无效。我已经将熊猫更新到了最新版本。有什么想法吗?

1 个答案:

答案 0 :(得分:3)

按列表使用列名称的参数名称,然后可以使用string dtype参数定义要解析为dictionary的列:

names = ["day", "time", "street", "sensor", "type", "state", "bits"]
df = pd.read_csv('EXPORT20171205114501_1.txt', sep="\s+", names=names, dtype={'bits':str})
print (df)
  day      time  street    sensor      type  state  bits
0  Tu  11:44:00     119  52913161  DETECTOR  STATE  0001
1  Tu  11:44:00     119  52913161  DETECTOR  STATE  1100
2  Tu  11:44:02     119  52913161  DETECTOR  STATE  0000
3  Tu  11:44:02     119  52913161  DETECTOR  STATE  1110
4  Tu  11:44:04     119  52913161  DETECTOR  STATE  0000
5  Tu  11:44:04     119  52913161  DETECTOR  STATE  0011

如果需要所有列作为字符串:

names = ["day", "time", "street", "sensor", "type", "state", "bits"]
df = pd.read_csv('EXPORT20171205114501_1.txt', sep="\s+", names=names, dtype=str)
print (df)
  day      time  street    sensor      type  state  bits
0  Tu  11:44:00     119  52913161  DETECTOR  STATE  0001
1  Tu  11:44:00     119  52913161  DETECTOR  STATE  1100
2  Tu  11:44:02     119  52913161  DETECTOR  STATE  0000
3  Tu  11:44:02     119  52913161  DETECTOR  STATE  1110
4  Tu  11:44:04     119  52913161  DETECTOR  STATE  0000
5  Tu  11:44:04     119  52913161  DETECTOR  STATE  0011