【发布时间】:2020-12-09 16:57:38
【问题描述】:
我有一个包含一列的数据框,col1。
#ds
col1
1001
27
1004
0000
ds.dtpyes
col1 object
但是,在本专栏中,python 将 1001, 27, 1004 识别为 float,将 0000 识别为 str。
我想像这样对列进行子串化:
#ds
col1 col_new
1001 10
27 00
1004 10
0000 00
10 00
但我得到了NaN:
ds['col_new'] = ds['col1'].str[:2]
#ds
col1 col_new
1001 NaN
27 NaN
1004 NaN
0000 00
有什么帮助吗?谢谢!
更新
我编辑了示例以使其更清晰。
对于只有两位数的,我需要在他们前面填写'00'。
例如,“27”为“0027”。
回答:
ds['col1'].astype(int).astype(str).str.zfill(4).str[:2]
【问题讨论】:
-
如果1001和1004是float的,为什么要变成10?
-
前导零对整数无效,仅供参考
-
df['col1'].astype(str).str[:2].str.zfill(2) -
@Chris 您的解决方案很棒。但我编辑了问题以使其更清楚
标签: python pandas data-manipulation