如何在pandas数据帧的每一行的开头添加动态数量的空格?

时间:2017-01-05 13:39:30

标签: python pandas dataframe

如何将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,' ') 

2 个答案:

答案 0 :(得分:3)

我认为您可以使用str.rjust

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

答案 1 :(得分:0)

这应该有效:

spaces = " " * 30
df['test1'] = [spaces[-len(i):] + i for i in df['test1']]