gpt4 book ai didi

python - 如何在 Pandas 数据框的每一行的开头添加动态数量的空格?

转载 作者:太空宇宙 更新时间:2023-11-03 15:59:06 25 4
gpt4 key购买 nike

我如何在 df 的每一行左侧填充足够的空格以确保该行总计 30 个字符?

我尝试沿着这条路走下去,但它没有用,我相信 ljust 已被弃用:

'{: <30}'.format(df['test1'])

目前:

>>> df['test1']
0 1234jjjjjjjdddd
1 1234jjjjjjjdd
2 1234jjjjjjjddddddddd
3 1234jjjjjjjddd
4 1234jjjjjjjdddddd

我在找什么:

>>> df['test1']
0 1234jjjjjjjdddd
1 1234jjjjjjjdd
2 1234jjjjjjjddddddddd
3 1234jjjjjjjddd
4 1234jjjjjjjdddddd

最终解决方案:

df['test1'] = df.test1.str.rjust(30,' ') 

最佳答案

我想你可以使用 str.rjust :

print (df.test1.str.rjust(30, ' '))
0 1234jjjjjjjdddd
1 1234jjjjjjjdd
2 1234jjjjjjjddddddddd
3 1234jjjjjjjddd
4 1234jjjjjjjdddddd
Name: test1, dtype: object

关于python - 如何在 Pandas 数据框的每一行的开头添加动态数量的空格?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41486565/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com