Reputation: 85
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
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
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
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