3

I have a dataframe with several columns. I use Jupyter. One of the columns is just strings, the particular column name is empty ' ':

df = pd.DataFrame([[""], [""], [""], ['*'], ['* <<']],
                  columns=[''],
                  index=[0, 1, 2, 3, 4])

print(df)

0    
1    
2    
3   * <<
4      *

How can I justify left, so it looks like this:

print(df)

0    
1    
2    
3   * <<
4   *

Note: if I just use df, instead of print(df), it justifies well.

4
  • 2
    Provide df[''].to_dict() to reproduce the data? Commented Sep 28, 2017 at 16:02
  • Possible duplicate of stackoverflow.com/questions/17232013/… Commented Sep 28, 2017 at 16:05
  • @Bharathshetty It's not duplicate, I have the opposite problem. Check carefully. Commented Sep 28, 2017 at 16:12
  • @hernanavella I dont know why but its aligned to left by default in my kernel. :) Commented Sep 28, 2017 at 16:13

1 Answer 1

4

Option 1
Use pd.Series.str.ljust

df.iloc[:, 0] = (lambda s: s.str.ljust(s.str.len().max()))(df.iloc[:, 0])
df

0      
1      
2      
3  *   
4  * <<
Sign up to request clarification or add additional context in comments.

2 Comments

can u elaborate a bit on what [:, 0] does, i'll need to adapt the answer to the real data where the index is different, so I want o know what exactly is that.Thanks.
Your column header is '' and I can't grab it with df["''"]. I need the column as a series in order to leverage pd.Series.str.ljust. So to solve the problem of having '' as a column header, I use positional indexing to grab that first column df.iloc[:, 0]

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.