正在寻找一种适用于df的连锁方法。
考虑以下DF。
Store
1
33
455
我要做的是确定长度并根据长度添加一个0。
我尝试了一个我认为可能有效的for循环
for s in df.Store:
if s.str.len() == 3:
"0" + s
但是这不起作用。
我还尝试将DF和每个变量一一切片
if df.Store == df[df['Store'].str.len() == 1]:
"0" + df.Store
但都不起作用,只是返回空白输出。
我正在使用对象dtype。
所需的输出:
Store
0001
0033
0455
答案 0 :(得分:2)
如果要在字符串的最大长度后附加0
值,可以用max
用Series.str.len
来计数长度:
df['Store'] = df['Store'].astype(str)
df['Store'] = df['Store'].str.zfill(df['Store'].str.len().max())
print (df)
Store
0 001
1 033
2 455
如果要通过标量附加0
:
df['Store'] = df['Store'].astype(str).str.zfill(4)
print (df)
Store
0 0001
1 0033
2 0455
答案 1 :(得分:1)
使用此:
df['Store'] = df['Store'].apply(lambda x: x.zfill(4))