Pandas : 用一个或几个 0 更新 int Series

Pandas : update int Series with one or several 0

我在 DF 中有一个 pandas 系列,就像这个 :

DF=pd.DataFrame([1,2,58,99,123,256],columns=["ID"])

    ID
0   1
1   2
2   58
3   99
4   123
5   256

我正在尝试修改“ID”列,以便具有类似这样的内容(总是三个字符,因此对于长度 <3 的数字有一个或两个零):

    ID
0   "001"
1   "002"
2   "058"
3   "099"
4   "123"
5   "256"

我尝试通过列表理解、astype(str)、replace() 和 str.len() 来实现这一点,如下所示:

DF["ID"]=[x.replace(x, i*"0"+x) for x,i in (DF["ID"].astype(str),int(DF[DF["ID"]].astype(str).len())-3)]

但后来我遇到了这个错误

KeyError: "None of [Int64Index([1, 2, 58, 99, 123, 256], dtype='int64')] are in the [columns]"

我该如何解决?

您收到的错误是因为您试图将 'ID' 系列中的值当作列标签列表来传递。 有一种更简单的方法可以使用 pandas apply 和 str.rjust() 方法将宽度设置为 3 以将字符串填充为 3 个字符:

df = pd.DataFrame(dict(ID=[1,2,58,99,123,256]))

df['ID'] = df['ID'].apply(lambda x: str(x).rjust(3,'0'))

输出:

    ID
0   "001"
1   "002"
2   "058"
3   "099"
4   "123"
5   "256"

你使用带格式的 f-strings

DF['ID'] = DF['ID'].apply(lambda v: f'{v:03d}')

输出(顺便说一句,这些是字符串)


    ID
0   001
1   002
2   058
3   099
4   123
5   256

在我看来最地道的方法是:

>>> DF['ID'] = DF['ID'].astype(str).str.rjust(3, '0')                           
>>> DF                                                                          
    ID
0  001
1  002
2  058
3  099
4  123
5  256