简体   繁体   English

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

[英]How do I add a dynamic number of white spaces to the beginning of each row of a pandas dataframe?

How would I pad each row of the df to the left with enough spaces to ensure the row totals 30 characters? 如何将df的每一行填充到左侧,并留有足够的空格以确保行总计30个字符?

I tried going down this path, but it didn't work and I believe ljust is deprecated: 我试着走这条路,但它没有工作,我相信ljust被弃用:

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

Currently: 目前:

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

What I'm looking for: 我在找什么:

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

Final Solution: 最终解决方案

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

I think you can use str.rjust : 我想你可以使用str.rjust

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

This should work: 这应该工作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在一行的开头添加一个数字(熊猫) - How to add a number in the beginning of a row (pandas) 通过在 pandas 中的每个组中添加以 1 开头的数字,在 dataframe 中添加新列 - Add new column in dataframe by adding number beginning by 1 in each groups in pandas 使用Python如何在Pandas数据帧中的每一行的范围内生成一个随机数? - Using Python how do I generate a random number within a range for each row in Pandas dataframe? 如何计算熊猫数据框每行中字符串组合的数量? - How to do I count the number of string combinations in each row of a pandas dataframe? 如何使用 Pandas 向 Dataframe 的每一行添加值? - How do you add Values to each row of the Dataframe Using Pandas? 如何根据每行中的条件将多个字符串添加到 pandas dataframe 中的列中? - How do I add multiple strings to a column in a pandas dataframe based on conditions in each row? 如何为 pandas dataframe 中的每一组添加一行? - How can I add one row for each group in pandas dataframe? 使用熊猫,如何逐行遍历数据帧,但每一行都是其自己的数据帧 - Using pandas, how do I loop through a dataframe row by row but with each row being its own dataframe 如何将PANDAS数据帧的一行添加到其余行? - How do I add one row of a PANDAS dataframe to the rest of the rows? 如何在pandas数据帧的第二行中添加列标题? - How do i add column header, in the second row in a pandas dataframe?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM