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
Subham
  • 397
  • 1
  • 6
  • 14

1 Answers1

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

Pygirl
  • 12,969
  • 5
  • 30
  • 43