Ale*_*lli 0 python numpy pandas
我有以下数据框,其中col_1是整数类型:
print(df)
col_1
100
200
00153
00164
Run Code Online (Sandbox Code Playgroud)
如果位数等于3,我想添加两个零。
final_col
00100
00200
00153
00164
Run Code Online (Sandbox Code Playgroud)
我尝试过:
df.col_1 = df.col_1.astype(int).astype(str)
df["final_col"] = np.where(len(df["col_1"]) == 3, "00" + df.col_1, df.col_1 )
Run Code Online (Sandbox Code Playgroud)
但是,它不会产生预期的输出(满足条件时,不会将两位数字相加)。
我该如何解决?
使用str.zfill:
df['final_col'] = df['col_1'].astype(str).str.zfill(5)
Run Code Online (Sandbox Code Playgroud)
[出去]
final_col
0 00100
1 00200
2 00153
3 00164
Run Code Online (Sandbox Code Playgroud)
更新,如果您只想准确填充 len 为 3 的位置,请使用感谢@yatu 指出:Series.where
df.col_1.where(df.col_1.str.len().ne(3),
df.col_1.astype(str).str.zfill(5))
Run Code Online (Sandbox Code Playgroud)
另一种使用方式series.str.pad():
df.col_1.astype(str).str.pad(5,fillchar='0')
Run Code Online (Sandbox Code Playgroud)
0 00100
1 00200
2 00153
3 00164
Run Code Online (Sandbox Code Playgroud)
您的解决方案应更新为:
(np.where(df["col_1"].astype(str).str.len()==3,
"00" + df["col_1"].astype(str),df["col_1"].astype(str)))
Run Code Online (Sandbox Code Playgroud)
但这在字符串的长度小于5且不等于3时不起作用,因此我建议您不要使用它。
# after converting it to str , you can foolow up list comprehension.\n\ndf=pd.DataFrame({'col':['100','200','00153','00164']})\ndf['col_up']=['00'+x if len(x)==3 else x for x in df.col ]\ndf\n\n###output\n\n col col_up\n0 100 00100\n1 200 00200\n2 00153 00153\n3 00164 00164\n\n\n ### based on the responses in comments \n %%timeit -n 10000\n df.col.str.pad(5,fillchar='0') \n142 \xc2\xb5s \xc2\xb1 5.47 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10000 loops each)\n\n\n %%timeit -n 10000\n ['00'+x if len(x)==3 else x for x in df.col ]\n21.1 \xc2\xb5s \xc2\xb1 952 ns per loop (mean \xc2\xb1 std. dev. of 7 runs, 10000 loops each)\n\n %%timeit -n 10000\n df.col.astype(str).str.pad(5,fillchar='0')\n243 \xc2\xb5s \xc2\xb1 7.02 \xc2\xb5s per loop (mean \xc2\xb1 std. dev. of 7 runs, 10000 loops each)\nRun Code Online (Sandbox Code Playgroud)\n
| 归档时间: |
|
| 查看次数: |
276 次 |
| 最近记录: |