ShanZhengYang ShanZhengYang - 1 year ago 103
Python Question

How to save a pandas dataframe such that there is no delimiter?

I have the following pandas dataframe:

import pandas as pd
df = pd.DataFrame(np.random.choice([0,1], (6,3)), columns=list('XYZ'))

X Y Z
0 1 0 1
1 1 1 0
2 0 0 0
3 0 1 1
4 0 1 1
5 1 1 1


Let's say I take the transpose and wish to save it

df = df.T

0 1 2 3 4 5
X 1 1 0 0 0 1
Y 0 1 0 1 1 1
Z 1 0 0 1 1 1


So, there three rows. I would like to save it in this format:

X 110001
Y 010111
Z 100111


I tried

df.to_csv("filename.txt", header=None, index=None, sep='')


However, this outputs an error:

TypeError: "delimiter" must be an 1-character string


Is it possible to save the dataframe in this manner, or is there some what to combine all columns into one? What is the most "pandas" solution?

Answer Source

Leave original df alone. Don't transpose.

df = pd.DataFrame(np.random.choice([0,1], (6,3)), columns=list('XYZ'))

df.astype(str).apply(''.join)

X    101100
Y    101001
Z    111110
dtype: object
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download