首页 > 解决方案 > 如果从 csv 文件读取数据框中的列,如何保持数字限制?

问题描述

我正在读取 csv 文件作为熊猫数据框。有一个名为“c_id”的列只包含数字。它将是 3 位数字。下面是csv内容

doc_id,c_id,functional_area,doc_type,capture_date,file_name
011,"023","AP","AP - CHECKS","2021-05-01","file-11"
012,"023","AP","AP - CHECKS","2021-05-02","file-12"
013,"023","AP","AP - CHECKS","2021-05-01","file-13"
014,"023","AP","AP - CHECKS","2021-05-01","file-13"

c_id 可能的其他值:“23”、23、005、9、234、430 等。

当我将其作为熊猫数据框读取时,我需要将该列保留为 3 位列。所以

如果在 csv 中,

"23" it should be 023 in dataframe. similarly
23 -> 023,
005 -> 005
9 -> 009 etc.

我怎样才能做到这一点?

dtypes = {'c_id': 'str'}   
df = pd.read_csv('test.csv', dtype = dtypes) 

我也尝试过使用 dtypes。但没有得到所需的结果。

标签: pythonpandasdataframe

解决方案


您提出的解决方案对我有用:

In [1]: df = pd.read_csv('test.csv', dtype={'c_id': 'str'})

In [2]: df
Out[2]: 
   doc_id c_id functional_area     doc_type capture_date file_name
0      11  023              AP  AP - CHECKS   2021-05-01   file-11
1      12  023              AP  AP - CHECKS   2021-05-02   file-12
2      13  023              AP  AP - CHECKS   2021-05-01   file-13
3      14  023              AP  AP - CHECKS   2021-05-01   file-13

如果要向长度不正确的字符串添加零填充,可以使用Series.str.zfill

df['c_id'] = df['c_id'].str.zfill(3)

推荐阅读