dirtyw0lf
dirtyw0lf

Reputation: 1958

Flattening dataframe with separator to variable

How to assign this to a variable instead of printing it?

print(*df.values.flatten(), sep=',')

Upvotes: 2

Views: 691

Answers (3)

jpp
jpp

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

jezrael
jezrael

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

Naga kiran
Naga kiran

Reputation: 4607

','.join(df1.values.flatten())

Upvotes: 1

Related Questions