python - 如果从 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。但没有得到所需的结果。
解决方案
您提出的解决方案对我有用:
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)
推荐阅读
- vb.net - Azure AD/令牌/证书/SQL - 我迷路了
- javascript - 如何使用 .includes 针对数组过滤数组?
- python - 如何重复音频wav文件,使其在python中至少长6秒
- xslt - 如何使用 SaxonEE 进行 XSLT
- javascript - 如何使用 svg 生成六边形的随机位置?
- python - 在 ResNet50 或任何深度学习模型中处理多个输入(图像、文本)数据
- javascript - 使用 map、filter、reduce 将对象数组转换为具有额外属性的对象数组
- windows - 迭代文件夹并获取命令行输入的文件名
- html - Rowspan not expanding
- javascript - 重叠功能不适用于某些日期格式