pvmlad
pvmlad

Reputation: 85

How to print a string and a dataframe in 1 print statement?

lets say I have the string "df" and the dataframe

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('ab'))

I can print "df" with:

print("df")

And I can print my dataframe with:

print(df)

Which prints:

   a  b
0  1  2
1  3  4

Now why can't I do the following command?

print("df" + df)

I was expecting to get the output:

df
   a  b
0  1  2
1  3  4

But I get error messages instead.

Upvotes: 1

Views: 6497

Answers (4)

Babul 7154
Babul 7154

Reputation: 81

Because + character is used to add a variable to another variable; for Example:

1)String concatenation

x = "I don't know "
y = "logic "
z=x+y
print("I am a programmer but "+z)

output

I am a programmer but I dont know  logic

2)combine two numbers

x = 4
y = 26
print(x + y)

output30

But Pandas DataFrame is two-dimensional size-mutable data structure with labeled axes (rows and columns)

you can't concatenate str to dataframe,you must seperate them using comma(,) to show dataframe output for example:

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('ab'))
print("df",df)

output

df    a  b
   0  1  2
   1  3  4

Upvotes: 1

Aivar Paalberg
Aivar Paalberg

Reputation: 5149

Another way is to use separator:

print('df', df, sep='\n')

Upvotes: 0

Nathan Thomas
Nathan Thomas

Reputation: 270

You were getting the error because you were trying to concatenate an object (the DataFrame) with a string. This should fix the problem:

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('ab'))
print("df \n", df)

#output
df 
   a  b
0  1  2
1  3  4

Upvotes: 0

marcuse
marcuse

Reputation: 3999

You have to seperate the dataframe from the string: print("string", df). You can not concatenate a string with a dataframe. Alternatively you can format the dataframe to a string: print("string" + str(df))

Full code:

df = pd.DataFrame([[1, 2], [3, 4]], columns=list('ab'))
print("string", df)

Upvotes: 0

Related Questions