python-3.x 如何根据Pandas的值计数来满足零

nhaq1z21  于 2023-03-04  发布在  Python
关注(0)|答案(2)|浏览(170)

我有一个 Dataframe ,其中年份列如下所示

Year
202
2021
2022
202
2019

我需要为所有包含"202"的列值添加"0"
我该怎么做呢
预期输出

Year
 2020
 2021
 2022
 2020
 2019

目前代码:

df['Year_1'] = df['Year'].str.len()
b1uwtaje

b1uwtaje1#

对于不太像1000的值,可以将其乘以10

df.loc[df.Year.lt(1000), 'Year'] *= 10
print (df)
   Year
0  2020
1  2021
2  2022
3  2020
4  2019

如果使用字符串,且字符串长度为3,则添加0

df.Year = df.Year.astype(str)

df.loc[df['Year'].str.len().eq(3), 'Year'] += '0'
print (df)
   Year
0  2020
1  2021
2  2022
3  2020
4  2019
fjaof16o

fjaof16o2#

看起来您想要ljust

df['Year'] = df['Year'].str.ljust(4, '0')

输出:

Year
0  2020
1  2021
2  2022
3  2020
4  2019

相关问题