2

I am sure this is a duplicate question. However I wasn't able to find that directed me correctly. I am new so would appreciate any help available.

import pandas as pd

df = pd.DataFrame(index=['A','B','C'], columns=['x','y'])

print(df)

print("df.iloc[0]['x']:", df.iloc[0]['x'])

print(f'''df.iloc[0]: {df.iloc[0]}''')

prints

x    y
A  NaN  NaN
B  NaN  NaN
C  NaN  NaN
df.iloc[0]['x']: nan
df.iloc[0]: x    NaN
y    NaN
Name: A, dtype: object

[Program finished]

A similar question but with numpy has already been answered. Now the question is how should I get the prefix aligned in the third output? The numpy equivalent for similar is

print("Array:", np.array2string(array1, prefix ='Array:'))

Edit 1: Expected Output :

df.iloc[0]: x    NaN
            y    NaN
Name: A, dtype: object
2
  • I didn't get it what do you mean by aligned? Commented Mar 13, 2021 at 16:01
  • posted expected output Commented Mar 13, 2021 at 16:11

1 Answer 1

2

try replacing \n with spaces:

p = df.iloc[0].to_string().replace('\n','\n'+' '*12)
print('{:<11} {}'.format('df.iloc[0]:',p))

df.iloc[0]: x    NaN
            y    NaN

Source

formating info

Sign up to request clarification or add additional context in comments.

3 Comments

I might sound noob but is that a syntax or you actually Counted till 12
@Subham: If there is a longer string then it will fail. yeah you are right I manually set it to 12 by counting.
@Subham: There is no other solution than this.

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.