Reputation: 1958
How to assign this to a variable instead of printing it?
print(*df.values.flatten(), sep=',')
Upvotes: 2
Views: 691
Reputation: 164773
print
will happily print string and non-string objects in a single statement. But when forming a string you have to perform the conversion explicitly. Here you can use map
with str.join
:
res = ','.join(map(str, df.values.flatten()))
Alternatively, you can convert your NumPy array to one containing strings:
res = ','.join(df.values.astype(str).flatten())
Upvotes: 1
Reputation: 863166
I think to need convert values to strings if possible some not strings columns and then call join
:
a = ','.join(df.astype(str).values.flatten())
Sample:
df = pd.DataFrame({
'A': ['b','b','c','d'],
'B': list(range(4))
})
print (df)
A B
0 b 0
1 b 1
2 c 2
3 d 3
a = ','.join(df.astype(str).values.flatten())
print (a)
b,0,b,1,c,2,d,3
print(*df.values.flatten(), sep=',')
b,0,b,1,c,2,d,3
Upvotes: 3